/// <summary> /// Todo :Need to be enhanced to return the correct public key but not used for now /// </summary> /// <param name="pem"></param> /// <param name="key"></param> /// <returns></returns> public static Ed25519PublicKeyParameters GetPublicKeyFromPrivateKey(Ed25519PrivateKeyParameters privateKey) { // get the public key from the private key Ed25519PublicKeyParameters publicKey = privateKey.GeneratePublicKey(); return(publicKey); }
public virtual AsymmetricCipherKeyPair GenerateKeyPair() { Ed25519PrivateKeyParameters privateKey = new Ed25519PrivateKeyParameters(random); Ed25519PublicKeyParameters publicKey = privateKey.GeneratePublicKey(); return(new AsymmetricCipherKeyPair(publicKey, privateKey)); }
/// <summary> /// Creates a new Link from the given builder, signs it and executes the GraphQL /// mutation. /// </summary> /// <typeparam name="TLinkData"></typeparam> /// <param name="linkBuilder">The linkBuilder<see cref="TraceLinkBuilder{TLinkData}"/></param> /// <returns>The <see cref="Task{TraceState{TState, TLinkData}}"/></returns> private async Task <TraceState <TState, TLinkData> > CreateLinkAsync <TLinkData>(TraceLinkBuilder <TLinkData> linkBuilder) { // extract signing key from config SdkConfig sdkConfig = await GetConfigAsync(); Ed25519PrivateKeyParameters signingPrivateKey = sdkConfig.SigningPrivateKey; // build the link TraceLink <TLinkData> link = linkBuilder.Build(); // sign the link link.Sign(signingPrivateKey.GetEncoded(), "[version,data,meta]"); string linkObjJson = JsonHelper.ToJson(link.ALink); Dictionary <string, object> linkObj = JsonHelper.ObjectToMap(link.GetLink()); Dictionary <string, object> dataObj = JsonHelper.ObjectToMap(((TraceLink <TLinkData>)link).FormData()); Dictionary <string, object> variables = new Dictionary <string, object> { ["link"] = linkObj, ["data"] = dataObj }; // Debug.WriteLine("Request : " + JsonHelper.ToJson(dataObj)); // execute graphql query GraphQLResponse jsonResponse = await this.client.GraphqlAsync(GraphQL.MUTATION_CREATELINK, variables, null, null); var trace = jsonResponse.Data.createLink.trace; return(this.MakeTraceState <TLinkData>(trace)); }
public void CanValidateSignature() { Ed25519KeyPairGenerator kpg = new Ed25519KeyPairGenerator(); kpg.Init(new Ed25519KeyGenerationParameters(Random)); AsymmetricCipherKeyPair kp = kpg.GenerateKeyPair(); Ed25519PrivateKeyParameters privateKey = (Ed25519PrivateKeyParameters)kp.Private; Ed25519PublicKeyParameters publicKey = (Ed25519PublicKeyParameters)kp.Public; var pubKeyBase64 = Convert.ToBase64String(publicKey.GetEncoded()); // create signature for item byte[] msg = new byte[Random.NextInt() & 255]; Random.NextBytes(msg); var signer = new Ed25519Signer(); signer.Init(true, privateKey); signer.BlockUpdate(msg, 0, msg.Length); byte[] signature = signer.GenerateSignature(); var signatureForAppCast = Convert.ToBase64String(signature); // verify signature var checker = new Ed25519Checker(NetSparkleUpdater.Enums.SecurityMode.Strict, pubKeyBase64); Assert.True(checker.VerifySignature(signatureForAppCast, msg) == NetSparkleUpdater.Enums.ValidationResult.Valid); }
/// <summary> /// Generates the specified force. /// </summary> /// <param name="force">if set to <c>true</c> [force].</param> /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns> public bool Generate(bool force = false) { if (KeysExist() && !force) { Console.WriteLine("Keys already exist, use --force to force regeneration"); return(false); } // start key generation Console.WriteLine("Generating key pair..."); var Random = new SecureRandom(); Ed25519KeyPairGenerator kpg = new Ed25519KeyPairGenerator(); kpg.Init(new Ed25519KeyGenerationParameters(Random)); AsymmetricCipherKeyPair kp = kpg.GenerateKeyPair(); Ed25519PrivateKeyParameters privateKey = (Ed25519PrivateKeyParameters)kp.Private; Ed25519PublicKeyParameters publicKey = (Ed25519PublicKeyParameters)kp.Public; var privKeyBase64 = Convert.ToBase64String(privateKey.GetEncoded()); var pubKeyBase64 = Convert.ToBase64String(publicKey.GetEncoded()); File.WriteAllText(_privateKeyFilePath, privKeyBase64); File.WriteAllText(_publicKeyFilePath, pubKeyBase64); Console.WriteLine("Storing public/private keys to " + _storagePath); return(true); }
/// <summary> /// Signs the passed in data with a private key /// </summary> /// <param name="privateKey">the private key used to create the signature</param> /// <param name="data">The data to sign</param> /// <returns>the signature as a byte array</returns> public byte[] Sign(byte[] privateKey, byte[] data) { Ed25519PrivateKeyParameters privKey = null; try { privKey = (Ed25519PrivateKeyParameters)CreateAsymmetricKeyParameterFromPrivateKeyInfo(privateKey); } catch (InvalidCastException exception) { string message = "Private Key Import Failed!\n" + $"{exception.Message}.\n" + "The contents of the source do not represent a valid Ed25519 key parameter\n" + "Verify that the key is not corrupted.\n" + "- or - Verify that the correct key is selected."; throw new CryptoException(message, exception); } var signer = new Ed25519Signer(); signer.Init(true, privKey); signer.BlockUpdate(data, 0, data.Length); var signature = signer.GenerateSignature(); return(signature); }
private void DoTestConsistency(Ed25519.Algorithm algorithm, byte[] context) { Ed25519KeyPairGenerator kpg = new Ed25519KeyPairGenerator(); kpg.Init(new Ed25519KeyGenerationParameters(Random)); AsymmetricCipherKeyPair kp = kpg.GenerateKeyPair(); Ed25519PrivateKeyParameters privateKey = (Ed25519PrivateKeyParameters)kp.Private; Ed25519PublicKeyParameters publicKey = (Ed25519PublicKeyParameters)kp.Public; byte[] msg = new byte[Random.NextInt() & 255]; Random.NextBytes(msg); ISigner signer = CreateSigner(algorithm, context); signer.Init(true, privateKey); signer.BlockUpdate(msg, 0, msg.Length); byte[] signature = signer.GenerateSignature(); ISigner verifier = CreateSigner(algorithm, context); { verifier.Init(false, publicKey); verifier.BlockUpdate(msg, 0, msg.Length); bool shouldVerify = verifier.VerifySignature(signature); if (!shouldVerify) { Fail("Ed25519(" + algorithm + ") signature failed to verify"); } } { byte[] wrongLengthSignature = Arrays.Append(signature, 0x00); verifier.Init(false, publicKey); verifier.BlockUpdate(msg, 0, msg.Length); bool shouldNotVerify = verifier.VerifySignature(wrongLengthSignature); if (shouldNotVerify) { Fail("Ed25519(" + algorithm + ") wrong length signature incorrectly verified"); } } { byte[] badSignature = Arrays.Clone(signature); badSignature[Random.Next() % badSignature.Length] ^= (byte)(1 << (Random.NextInt() & 7)); verifier.Init(false, publicKey); verifier.BlockUpdate(msg, 0, msg.Length); bool shouldNotVerify = verifier.VerifySignature(badSignature); if (shouldNotVerify) { Fail("Ed25519(" + algorithm + ") bad signature incorrectly verified"); } } }
/// <summary> /// Encodes private key to PEM formatted string /// </summary> /// <param name="publicKey"></param> /// <returns></returns> public static string EncodePrivateKey(Ed25519PrivateKeyParameters privateKey) { var serializedPublicBytes = privateKey.GetEncoded(); var base64 = Convert.ToBase64String(serializedPublicBytes); base64 = string.Format("-----BEGIN ED25519 PRIVATE KEY-----\n{0}\n-----END ED25519 PRIVATE KEY-----\n", base64); return(base64); }
public RawKeyPair(string privateKey) { string privateKey32 = privateKey.Length == 128 ? privateKey.Substring(0, 64) : privateKey; Ed25519PrivateKeyParameters privateKeyParams = new Ed25519PrivateKeyParameters(Hex.Decode(privateKey32), 0); Ed25519PublicKeyParameters publicKeyParams = privateKeyParams.GeneratePublicKey(); PublicKey = publicKeyParams.GetEncoded(); PrivateKey = privateKeyParams.GetEncoded(); }
public SdkConfig(string workflowId, string configId, string accountId, Dictionary <string, string> groupLabelToIdMap, Ed25519PrivateKeyParameters signingPrivateKey) { this.workflowId = workflowId; this.configId = configId; this.accountId = accountId; this.groupLabelToIdMap = groupLabelToIdMap; this.signingPrivateKey = signingPrivateKey; }
/// <summary> /// Signg the message and convert it ot base64 /// </summary> /// <param name="key"></param> /// <param name="message"></param> /// <returns></returns> public static string Sign(Ed25519PrivateKeyParameters key, byte[] message) { ISigner signer = SignerUtilities.GetSigner(Ed25519_ALGO); signer.Init(true, key); signer.BlockUpdate(message, 0, message.Length); var signature = signer.GenerateSignature(); return(CryptoUtils.EncodeSignature(signature)); }
public SdkConfig(string workflowId, string userId, string accountId, string groupId, string ownerId, IDictionary <string, string> actionNames, Ed25519PrivateKeyParameters signingPrivateKey) { this.workflowId = workflowId; this.userId = userId; this.accountId = accountId; this.groupId = groupId; this.ownerId = ownerId; this.signingPrivateKey = signingPrivateKey; this.actionNames = actionNames; }
public AsymmetricKeyPair Generate() { Ed25519PrivateKeyParameters secretKeyParams = new Ed25519PrivateKeyParameters(_secureRandom); Ed25519PublicKeyParameters publicKeyParams = secretKeyParams.GeneratePublicKey(); byte[] asn1SecretKey = SecretKeyAsn1Header.Concat(secretKeyParams.GetEncoded()).ToArray(); byte[] asn1PublicKey = PublicKeyAsn1Header.Concat(publicKeyParams.GetEncoded()).ToArray(); return(new AsymmetricKeyPair(new SecretKey(asn1SecretKey, KeyAlgorithm.Ed25519), new PublicKey(asn1PublicKey, KeyAlgorithm.Ed25519))); }
public BaseKeyPair(string privateKey) { string privateKey32 = privateKey.Length == 128 ? privateKey.Substring(0, 64) : privateKey; Ed25519PrivateKeyParameters privateKeyParams = new Ed25519PrivateKeyParameters(Hex.Decode(privateKey32), 0); Ed25519PublicKeyParameters publicKeyParams = privateKeyParams.GeneratePublicKey(); byte[] publicBinary = publicKeyParams.GetEncoded(); byte[] privateBinary = privateKeyParams.GetEncoded(); PublicKey = Encoding.EncodeCheck(publicBinary, Constants.ApiIdentifiers.ACCOUNT_PUBKEY); PrivateKey = Hex.ToHexString(privateBinary) + Hex.ToHexString(publicBinary); }
public Signature Sign(byte[] msg, byte[] prvKey) { var digest = Blake2b.GetDigest(msg); var privateKey = new Ed25519PrivateKeyParameters(prvKey, 0); var signer = new Ed25519Signer(); signer.Init(true, privateKey); signer.BlockUpdate(digest, 0, digest.Length); return(new Signature(signer.GenerateSignature(), _SignaturePrefix)); }
public static RawKeyPair Generate() { Ed25519KeyPairGenerator keyPairGenerator = new Ed25519KeyPairGenerator(); keyPairGenerator.Init(new Ed25519KeyGenerationParameters(new SecureRandom())); AsymmetricCipherKeyPair asymmetricCipherKeyPair = keyPairGenerator.GenerateKeyPair(); Ed25519PublicKeyParameters publicKeyParams = (Ed25519PublicKeyParameters)asymmetricCipherKeyPair.Public; Ed25519PrivateKeyParameters privateKeyParams = (Ed25519PrivateKeyParameters)asymmetricCipherKeyPair.Private; byte[] publicKey = publicKeyParams.GetEncoded(); byte[] privateKey = privateKeyParams.GetEncoded(); return(new RawKeyPair(publicKey, privateKey)); }
/// <summary> /// Creates a new Link from the given builder, signs it and executes the GraphQL /// mutation. /// </summary> /// <typeparam name="TLinkData"></typeparam> /// <param name="linkBuilder">The linkBuilder<see cref="TraceLinkBuilder{TLinkData}"/></param> /// <param name="firstTry">if this is not the first try, do not retry</param> /// <returns>The <see cref="Task{TraceState{TState, TLinkData}}"/></returns> private async Task <TraceState <TState, TLinkData> > CreateLinkAsync <TLinkData>(TraceLinkBuilder <TLinkData> linkBuilder, bool firstTry = true) { // extract signing key from config SdkConfig sdkConfig = await GetConfigAsync(); Ed25519PrivateKeyParameters signingPrivateKey = sdkConfig.SigningPrivateKey; // build the link TraceLink <TLinkData> link = linkBuilder.Build(); // sign the link link.Sign(signingPrivateKey.GetEncoded(), "[version,data,meta]"); string linkObjJson = JsonHelper.ToJson(link.ALink); Dictionary <string, object> linkObj = JsonHelper.ObjectToMap(link.GetLink()); Dictionary <string, object> dataObj = JsonHelper.ObjectToMap(((TraceLink <TLinkData>)link).FormData()); Dictionary <string, object> variables = new Dictionary <string, object> { ["link"] = linkObj, ["data"] = dataObj }; try { // execute graphql query GraphQLResponse <dynamic> jsonResponse = await this.client.GraphqlAsync(GraphQL.MUTATION_CREATELINK, variables, null, null); var trace = jsonResponse.Data.createLink.trace; return(this.MakeTraceState <TLinkData>(trace)); } catch (TraceSdkException e) { if (firstTry && e.Message == ERROR_CONFIG_DEPRECATED) { var cfg = await this.GetConfigAsync(true); linkBuilder.WithConfigId(cfg.ConfigId); link.GetLink().Signatures.Clear(); return(await this.CreateLinkAsync(linkBuilder, false)); } throw e; } }
public void TestSign() { try { Ed25519PrivateKeyParameters pri = CryptoUtils.DecodeEd25519PrivateKey(privateKey); String encodedSig = CryptoUtils.Sign(pri, msg); Assert.AreEqual(encodedSig.Trim(), signature.Trim(), "Encoded message does not match expected"); } catch (Exception e) { System.Diagnostics.Debug.WriteLine(e.ToString()); throw e; } }
internal static void Sign(IInvoice invoice, Ed25519PrivateKeyParameters privateKey) { var ed25519Signer = new Ed25519Signer(); ed25519Signer.Init(true, privateKey); ed25519Signer.BlockUpdate(invoice.TxBytes.ToArray(), 0, invoice.TxBytes.Length); var signature = ed25519Signer.GenerateSignature(); ed25519Signer.Reset(); var publicKey = privateKey.GeneratePublicKey().GetEncoded(); var prefix = new ReadOnlyMemory <byte>(publicKey, 0, Math.Min(Math.Max(6, invoice.MinimumDesiredPrefixSize), publicKey.Length)); invoice.AddSignature(KeyType.Ed25519, prefix, signature); }
internal byte[] GenerateSignature(Ed25519PrivateKeyParameters privateKey, Ed25519PublicKeyParameters publicKey) { #if PORTABLE byte[] buf = ToArray(); int count = buf.Length; #else byte[] buf = GetBuffer(); int count = (int)Position; #endif byte[] signature = new byte[Ed25519PrivateKeyParameters.SignatureSize]; privateKey.Sign(Ed25519.Algorithm.Ed25519, publicKey, null, buf, 0, count, signature, 0); Reset(); return(signature); }
string ITestCase.Generate() { Ed25519PrivateKeyParameters privateKey = CryptoUtils.DecodeEd25519PrivateKey(privateKeyString); Link link = new LinkBuilder("test_process", "test_map") .WithAction("ʙᴀᴛᴍᴀɴ").Build(); link.Sign(privateKey.GetEncoded(), ""); link.Sign(privateKey.GetEncoded(), "[version,meta.mapId]"); // link.sign(rsaKey.getEncoded(), "[version,meta.mapId]"); Segment segment = link.Segmentify(); return(Convert.ToBase64String(segment.Serialize())); }
public void TestGetPublicKeyFromPrivateKey() { try { Ed25519PrivateKeyParameters pri = CryptoUtils.DecodeEd25519PrivateKey(privateKey); Ed25519PublicKeyParameters pub = CryptoUtils.GetPublicKeyFromPrivateKey(pri); string publicPEM = CryptoUtils.EncodePublicKey(pub); Assert.AreEqual(publicPEM, publicKey, "Extract public key from private key failed"); } catch (Exception e) { System.Diagnostics.Debug.WriteLine(e.ToString()); throw e; } }
public void Init(bool forSigning, ICipherParameters parameters) { if (forSigning) { privateKey = (Ed25519PrivateKeyParameters)parameters; publicKey = privateKey.GeneratePublicKey(); } else { publicKey = (Ed25519PublicKeyParameters)parameters; privateKey = null; } Reset(); }
public void TestSignVerify() { try { Ed25519PrivateKeyParameters pri = CryptoUtils.DecodeEd25519PrivateKey(privateKey); Ed25519PublicKeyParameters pub = CryptoUtils.GetPublicKeyFromPrivateKey(pri); String encodedSig = CryptoUtils.Sign(pri, msg); Assert.IsTrue(CryptoUtils.Verify(pub, msg, encodedSig), "Message Verification failed"); } catch (Exception e) { System.Diagnostics.Debug.WriteLine(e.ToString()); throw e; } }
/// <summary> /// Rebuild the account from private key /// </summary> /// <param name="privateKey">Private Key</param> /// <returns>the rebuilded account</returns> public static Account AccountFromPrivateKey(byte[] privateKey) { if (privateKey.Length != SK_SIZE) { throw new ArgumentException("Incorrect private key length"); } var privateKeyRebuild = new Ed25519PrivateKeyParameters(privateKey, 0); var publicKeyRebuild = privateKeyRebuild.GeneratePublicKey(); var act = new Account { privateKeyPair = new AsymmetricCipherKeyPair(publicKeyRebuild, privateKeyRebuild), }; act.Address = new Address(act.GetClearTextPublicKey()); return(act); }
internal byte[] GenerateSignature(Ed25519PrivateKeyParameters privateKey, byte[] ctx) { lock (this) { #if PORTABLE || NETFX_CORE byte[] buf = ToArray(); int count = buf.Length; #else byte[] buf = GetBuffer(); int count = (int)Position; #endif byte[] signature = new byte[Ed25519PrivateKeyParameters.SignatureSize]; privateKey.Sign(Ed25519.Algorithm.Ed25519ctx, ctx, buf, 0, count, signature, 0); Reset(); return(signature); } }
public virtual void Init(bool forSigning, ICipherParameters parameters) { this.forSigning = forSigning; if (forSigning) { this.privateKey = (Ed25519PrivateKeyParameters)parameters; this.publicKey = null; } else { this.privateKey = null; this.publicKey = (Ed25519PublicKeyParameters)parameters; } Reset(); }
public static KeyPair generateEd25519KeyPair() { Org.BouncyCastle.Crypto.Generators.Ed25519KeyPairGenerator kpg = new Org.BouncyCastle.Crypto.Generators.Ed25519KeyPairGenerator(); kpg.Init(new Ed25519KeyGenerationParameters(secureRandom)); Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair kp = kpg.GenerateKeyPair(); KeyPair nkp = new KeyPair(); Ed25519PrivateKeyParameters privateKey = (Ed25519PrivateKeyParameters)kp.Private; Ed25519PublicKeyParameters publicKey = (Ed25519PublicKeyParameters)kp.Public; nkp.publicKey = new PublicKey(publicKey.GetEncoded()); nkp.privateKey = new PrivateKey(privateKey.GetEncoded()); if (nkp.privateKey.isValid()) { return(nkp); } return(generateEd25519KeyPair()); }
public override bool GenerateKey(byte[] inSeed, byte[] outKey, int accessLevel, List <Parameter> parameters) { byte[] privateKeyBytes = GetParameterBytearray(parameters, "PrivateKey"); if ((inSeed.Length != 32) || (outKey.Length != 64)) { return(false); } Ed25519PrivateKeyParameters privateKey = new Ed25519PrivateKeyParameters(privateKeyBytes, 0); Ed25519phSigner signer = new Ed25519phSigner(new byte[] { }); signer.Init(true, privateKey); signer.BlockUpdate(inSeed, 0, inSeed.Length); byte[] signature = signer.GenerateSignature(); Array.ConstrainedCopy(signature, 0, outKey, 0, signature.Length); return(true); }
public virtual void Init(bool forSigning, ICipherParameters parameters) { this.forSigning = forSigning; if (forSigning) { // TODO Allow AsymmetricCipherKeyPair to be a CipherParameters? this.privateKey = (Ed25519PrivateKeyParameters)parameters; this.publicKey = privateKey.GeneratePublicKey(); } else { this.privateKey = null; this.publicKey = (Ed25519PublicKeyParameters)parameters; } Reset(); }