/// <summary> /// Verify the provided data and signature match this keypair's public key. /// </summary> /// <param name="data">The data that was signed.</param> /// <param name="signature">The signature.</param> /// <returns>True if they match, false otherwise.</returns> public bool Verify(byte[] data, byte[] signature) { bool result = false; try { result = Ed25519.Verify(signature, data, PublicKey); } catch { result = false; } return(result); }
private static ICryptoService GetRandomCryptoService() { ICryptoService cryptoService = Substitute.For <ICryptoService>(); byte[] privateKey = CryptoHelper.GetRandomSeed(); byte[] expandedPrivateKey; byte[] publicKey; Ed25519.KeyPairFromSeed(out publicKey, out expandedPrivateKey, privateKey); cryptoService.Sign(null).ReturnsForAnyArgs(c => Ed25519.Sign(c.Arg <byte[]>(), expandedPrivateKey)); cryptoService.PublicKey.Returns(new Key32() { Value = publicKey }); return(cryptoService); }
public void SignVerifyTest() { RandomNumberGenerator random = RNGCryptoServiceProvider.Create(); byte[] bPriKey = new byte[32]; random.GetBytes(bPriKey); byte[] bExpPriKey = Ed25519.ExpandedPrivateKeyFromSeed(bPriKey); byte[] bPubKey = Ed25519.PublicKeyFromSeed(bPriKey); byte[] msg = new byte[] { 0x1, 0x2, 0x3, 0x4 }; byte[] sign = Ed25519.Sign(msg, bExpPriKey); Assert.True(Ed25519.Verify(sign, msg, bPubKey)); }
public static void ScalarMultBase(byte[] k, int kOff, byte[] r, int rOff) { int[] y = F.Create(); int[] z = F.Create(); Ed25519.ScalarMultBaseYZ(k, kOff, y, z); F.Apm(z, y, y, z); F.Inv(z, z); F.Mul(y, z, y); F.Normalize(y); F.Encode(y, r, rOff); }
/// <summary> /// Creates from private key. /// </summary> /// <param name="privateKey">The private key.</param> /// <returns>KeyPair.</returns> /// <exception cref="ArgumentNullException">privateKey</exception> /// <exception cref="ArgumentException">privateKey</exception> public static KeyPair CreateFromPrivateKey(string privateKey) { if (privateKey == null) { throw new ArgumentNullException(nameof(privateKey)); } if (privateKey.Length != 64) { throw new ArgumentException(nameof(privateKey)); } var privateKeyArray = privateKey.FromHex(); return(new KeyPair(privateKey, Ed25519.PublicKeyFromSeed(privateKeyArray).ToHexLower())); }
/// <summary> /// Verifies the specified message. /// </summary> /// <param name="message">The message.</param> /// <param name="signature">The signature.</param> /// <param name="key">The public key.</param> /// <returns><c>true</c> if verified, <c>false</c> otherwise.</returns> public bool Verify(byte[] message, byte[] signature, byte[] key) { // Using Paseto Cryptography library return(Ed25519.Verify(signature, message, key)); /* * Using NSec library * * var algo = new Ed25519(); * var publicKey = PublicKey.Import(algo, key, KeyBlobFormat.RawPublicKey); * algo.Verify(publicKey, message, signature); */ // Using Sodium Core library //return PublicKeyAuth.VerifyDetached(signature, message, key); }
/// <summary> /// Generates a 64-bit signature of the given message. /// </summary> /// <param name="message">A byte array of any size.</param> /// <param name="privateKey32">32-byte private key.</param> /// <returns>Signature and public key.</returns> public static LoomCryptoSignature Sign(byte[] message, byte[] privateKey32) { if (privateKey32.Length != 32) { throw new System.ArgumentException("Expected 32-byte array", "privateKey"); } byte[] publicKey32; byte[] privateKey64; Ed25519.KeyPairFromSeed(out publicKey32, out privateKey64, privateKey32); byte[] signature = Ed25519.Sign(message, privateKey64); return(new LoomCryptoSignature { Signature = signature, PublicKey = publicKey32 }); }
public static byte[] CreateToken(string identification, long number, byte[] privateKey) { if (identification.Contains(";")) { throw new InvalidTokenException("The provided token has not the expected format"); } var encodedData = Encode(identification, number); var signature = Ed25519.Sign(encodedData, privateKey); var mergedArray = new byte[encodedData.Length + signature.Length]; Buffer.BlockCopy(encodedData, 0, mergedArray, 0, encodedData.Length); Buffer.BlockCopy(signature, 0, mergedArray, encodedData.Length, signature.Length); return(mergedArray); }
public static void Test(string sk, string pk, string msg, string sig) { var a = new Ed25519(); using (var k = Key.Import(a, sk.DecodeHex().Substring(0, 32), KeyBlobFormat.RawPrivateKey)) { var p = PublicKey.Import(a, pk.DecodeHex(), KeyBlobFormat.RawPublicKey); var m = msg.DecodeHex(); var expected = sig.DecodeHex().Substring(0, a.SignatureSize); var actual = a.Sign(k, m); Assert.Equal(expected, actual); Assert.True(a.TryVerify(p, m, expected)); } }
private static void ImportSeed() { Console.ForegroundColor = ConsoleColor.DarkGreen; Console.WriteLine("Import mnemonic"); Console.ForegroundColor = ConsoleColor.Gray; Console.Write("Enter words: "); mnemonic = Console.ReadLine(); Console.Write("Enter password or press Enter: "); string pass = Console.ReadLine(); var bip = new BIP39(mnemonic, pass); var seed = new ArraySegment <byte>(bip.SeedBytes, 0, Ed25519.PrivateKeySeedSizeInBytes); Ed25519.KeyPairFromSeed(out publicKey, out privateKey, seed.ToArray()); tz1 = CryptoServices.CreatePrefixedHash(HashType.PublicKeyHash, publicKey); edsk = CryptoServices.EncodePrefixed(HashType.Private, privateKey); }
public void CreateTestNetAccount() { RandomNumberGenerator random = RNGCryptoServiceProvider.Create(); byte[] bPriKey = new byte[32]; random.GetBytes(bPriKey); byte[] bExpPriKey = Ed25519.ExpandedPrivateKeyFromSeed(bPriKey); byte[] bPubKey = Ed25519.PublicKeyFromSeed(bPriKey); string addr = Account.Create(bPubKey, NetType.Test_Net); NetType netType = NetType.Public_Net; bool bOk = Account.Verify(addr, out netType); Assert.True(bOk && netType == NetType.Test_Net); }
/// <summary> /// verify signed message using a key /// </summary> /// <param name="publicKey"></param> /// <param name="sign"></param> /// <param name="message"></param> /// <returns></returns> /// <exception cref="InvalidOperationException">Invalid public key format</exception> /// <exception cref="InvalidOperationException">Invalid signature format</exception> public static bool VerifyMessage(byte[] publicKey, byte[] sign, byte[] message) { if (publicKey == null || publicKey.Length != 32) { throw new InvalidOperationException("Invalid public key format"); } if (sign == null || sign.Length != 64) { throw new InvalidOperationException("Invalid signature format"); } Ed25519 ed25519 = new Ed25519(); ed25519.FromPublicKey(publicKey); return(ed25519.VerifyMessage(message, sign)); }
internal bool VerifySignature(Ed25519PublicKeyParameters publicKey, byte[] ctx, byte[] signature) { lock (this) { #if PORTABLE byte[] buf = ToArray(); int count = buf.Length; #else byte[] buf = GetBuffer(); int count = (int)Position; #endif byte[] pk = publicKey.GetEncoded(); bool result = Ed25519.Verify(signature, 0, pk, 0, ctx, buf, 0, count); Reset(); return(result); } }
/// <summary> /// Generates a 64-byte private key from a 32-byte seed. /// </summary> /// <param name="privateKeySeed">32-byte private key seed.</param> /// <returns>A 64-byte array.</returns> public static byte[] GeneratePrivateKey(byte[] privateKeySeed) { if (privateKeySeed == null) { throw new ArgumentNullException("privateKeySeed"); } if (privateKeySeed.Length != 32) { throw new ArgumentException("Expected a 32-byte array", "privateKeySeed"); } byte[] publicKey32; byte[] privateKey64; Ed25519.KeyPairFromSeed(out publicKey32, out privateKey64, privateKeySeed); return(privateKey64); }
public void MalleabilityAddL() { var message = Enumerable.Range(0, 100).Select(i => (byte)i).ToArray(); byte[] pk; byte[] sk; Ed25519.KeyPairFromSeed(out pk, out sk, new byte[32]); var signature = Ed25519.Sign(message, sk); Assert.IsTrue(Ed25519.Verify(signature, message, pk)); var modifiedSignature = AddLToSignature(signature); Assert.IsTrue(Ed25519.Verify(modifiedSignature, message, pk)); var modifiedSignature2 = AddLToSignature(modifiedSignature); Assert.IsFalse(Ed25519.Verify(modifiedSignature2, message, pk)); }
public void VerifyFail() { var message = Enumerable.Range(0, 100).Select(i => (byte)i).ToArray(); Ed25519.KeyPairFromSeed(out var pk, out var sk, new byte[32]); var signature = Ed25519.Sign(message, sk); Assert.IsTrue(Ed25519.Verify(signature, message, pk)); foreach (var modifiedMessage in message.WithChangedBit()) { Assert.IsFalse(Ed25519.Verify(signature, modifiedMessage, pk)); } foreach (var modifiedSignature in signature.WithChangedBit()) { Assert.IsFalse(Ed25519.Verify(modifiedSignature, message, pk)); } }
public static string GenJwtAuthCode(string method, string uri, string body, string clientId, string sessionId, string priKey) { byte[] bsha256 = null; using (SHA256 mySHA256 = SHA256.Create()) { bsha256 = mySHA256.ComputeHash(Encoding.UTF8.GetBytes(method + uri + body)); } var bPriToken = UrlBase64.Decode(priKey); Ed25519 edkey = (Ed25519)Ed25519.Create("ed25519-sha512"); edkey.FromPrivateKey(bPriToken); var payload = new Dictionary <string, object>() { { "uid", clientId }, { "sid", sessionId }, { "iat", ToUnixTime(DateTime.UtcNow) }, { "exp", ToUnixTime(DateTime.UtcNow) + 3600 * 24 }, //过期时间暂定一天 { "jti", Guid.NewGuid().ToString() }, { "sig", BCD2ASC(bsha256) }, { "scp", "FULL" } }; var header = new Dictionary <string, object>() { { "alg", "EdDSA" }, { "typ", "JWT" }, { "kty", "OKP" }, { "crv", "Ed25519" }, { "x", UrlBase64.Encode(edkey.GetPublicKey()) } }; var szHeader = JsonConvert.SerializeObject(header); var szPayload = JsonConvert.SerializeObject(payload); var signData = UrlBase64.Encode(Encoding.ASCII.GetBytes(szHeader)) + "." + UrlBase64.Encode(Encoding.ASCII.GetBytes(szPayload)); string sign = UrlBase64.Encode(edkey.SignMessage(Encoding.ASCII.GetBytes(signData))); return(signData + "." + sign); }
public static void PkixPublicKeyText() { var a = new Ed25519(); var b = Utilities.RandomBytes.Slice(0, a.PrivateKeySize); using (var k = Key.Import(a, b, KeyBlobFormat.RawPrivateKey)) { var expected = Encoding.UTF8.GetBytes( "-----BEGIN PUBLIC KEY-----\r\n" + Convert.ToBase64String(k.Export(KeyBlobFormat.PkixPublicKey)) + "\r\n" + "-----END PUBLIC KEY-----\r\n"); var actual = k.Export(KeyBlobFormat.PkixPublicKeyText); Assert.Equal(expected, actual); } }
public void SwapToken(Address buyer, Address seller, string baseSymbol, string quoteSymbol, BigInteger tokenID, BigInteger price, byte[] signature) { Runtime.Expect(Runtime.IsWitness(buyer), "invalid witness"); Runtime.Expect(seller != buyer, "invalid seller"); Runtime.Expect(seller.IsUser, "seller must be user address"); Runtime.Expect(Runtime.TokenExists(baseSymbol), "invalid base token"); var baseToken = Runtime.GetToken(baseSymbol); Runtime.Expect(!baseToken.Flags.HasFlag(TokenFlags.Fungible), "token must be non-fungible"); var nft = Runtime.ReadToken(baseSymbol, tokenID); Runtime.Expect(nft.CurrentChain == Runtime.Chain.Name, "invalid owner"); var owner = nft.CurrentOwner; Runtime.Expect(owner == seller, "invalid owner"); var swap = new TokenSwap() { baseSymbol = baseSymbol, quoteSymbol = quoteSymbol, buyer = buyer, seller = seller, price = price, value = tokenID, }; var msg = Serialization.Serialize(swap); Runtime.Expect(Ed25519.Verify(signature, msg, seller.ToByteArray().Skip(1).ToArray()), "invalid signature"); Runtime.Expect(Runtime.TokenExists(quoteSymbol), "invalid quote token"); var quoteToken = Runtime.GetToken(quoteSymbol); Runtime.Expect(quoteToken.Flags.HasFlag(TokenFlags.Fungible), "token must be fungible"); var balance = Runtime.GetBalance(quoteSymbol, buyer); Runtime.Expect(balance >= price, "invalid balance"); Runtime.TransferTokens(quoteSymbol, buyer, owner, price); Runtime.TransferToken(baseSymbol, owner, buyer, tokenID); }
public void DJB_Ed25519_Blake2B512() { byte[] data = TEST; var digest = new Blake2BDigest(512); var m = new byte[digest.OutputSize]; digest.BlockUpdate(data, 0, data.Length); digest.DoFinal(m, 0); ECKeypair keypair = KeypairFactory.GenerateECKeypair(DjbCurve.Ed25519.ToString()); byte[] sig = Ed25519.Sign(m, keypair.EncodedPrivateKey); bool good = Ed25519.Verify(sig, m, keypair.EncodedPublicKey); Assert.IsTrue(good); }
public static byte[] GetSignedPacket(PacketType packetType, ulong syncBlockHeight, uint nonce, byte[] powHash, ushort version, ushort blockType, ulong blockHeight, byte[] prevHash, byte[] body, byte[] privateKey, out byte[] signature) { byte[] result = null; byte[] bodyBytes = null; using (MemoryStream ms = new MemoryStream()) { using (BinaryWriter bw = new BinaryWriter(ms)) { bw.Write(version); bw.Write(blockType); bw.Write(blockHeight); if (prevHash != null) { bw.Write(prevHash); } bw.Write(body); } bodyBytes = ms.ToArray(); } byte[] publickKey = Ed25519.PublicKeyFromSeed(privateKey); byte[] expandedPrivateKey = Ed25519.ExpandedPrivateKeyFromSeed(privateKey); signature = Ed25519.Sign(bodyBytes, expandedPrivateKey); using (MemoryStream ms = new MemoryStream()) { using (BinaryWriter bw = new BinaryWriter(ms)) { bw.Write((ushort)packetType); bw.Write(syncBlockHeight); bw.Write(nonce); bw.Write(powHash); bw.Write(bodyBytes); bw.Write(signature); bw.Write(publickKey); } result = ms.ToArray(); } return(result); }
public void Test_SignPreKey() { ECPrivKeyModel priv = new ECPrivKeyModel(SharedUtils.HexStringToByteArray("1498b5467a63dffa2dc9d9e069caf075d16fc33fdd4c3b01bfadae6433767d93")); ECPubKeyModel pub = new ECPubKeyModel(SharedUtils.HexStringToByteArray("b7a3c12dc0c8c748ab07525b701122b88bd78f600c76342d27f25e5f92444cde")); IdentityKeyPairModel identityKeyPair = new IdentityKeyPairModel(priv, pub); for (uint id = 1; id < 250; id++) { byte[] data = Encoding.ASCII.GetBytes("Message for Ed25519 signing"); byte[] signature = new byte[Ed25519.SignatureSize]; Ed25519.Sign(identityKeyPair.privKey.key, 0, data, 0, data.Length, signature, 0); byte[] sigRef = SharedUtils.HexStringToByteArray("6dd355667fae4eb43c6e0ab92e870edb2de0a88cae12dbd8591507f584fe4912babff497f1b8edf9567d2483d54ddc6459bea7855281b7a246a609e3001a4e08"); string sigRefBase64 = Convert.ToBase64String(sigRef); string sigBase64 = Convert.ToBase64String(signature); Assert.AreEqual(sigBase64, sigRefBase64); } }
internal NkeyPair(byte[] userSeed) { if (userSeed == null) { throw new NATSException("seed cannot be null"); } int len = userSeed.Length; if (len != Ed25519.PrivateKeySeedSize) { throw new NATSException("invalid seed length"); } seed = new byte[len]; Buffer.BlockCopy(userSeed, 0, seed, 0, len); Ed25519.KeyPairFromSeed(out key, out expandedPrivateKey, seed); }
private char ValidateVersion(DataRow input) { string[] inputValues = new string[input.ItemArray.Length]; Array.Copy(input.ItemArray, inputValues, input.ItemArray.Length); string name = inputValues[0], platform = inputValues[1], sign = inputValues[2]; var ver = Encoding.ASCII.GetBytes(platform + name); Ed25519 ed = new Ed25519(); ed.FromPublicKey(publicKey); if (!ed.VerifyMessage(ver, Convert.FromBase64String(sign))) { return('\u2718'); } return('\u2714'); }
internal static Ed25519Key KeyExchangeInternal(Ed25519Key privateKey, Ed25519Key publicKey) { if (privateKey == null || !privateKey.IsPrivate) { throw new ArgumentException("Invalid Private Key", nameof(privateKey)); } if (publicKey == null) { throw new ArgumentException("Invalid Public Key", nameof(privateKey)); } var sharedKeyData = new byte[32]; Ed25519.KeyExchange(new ArraySegment <byte>(sharedKeyData), publicKey.RawData, privateKey.RawData); return(new Ed25519Key(sharedKeyData)); }
/// <summary> /// Signs the specified message. /// </summary> /// <param name="message">The message.</param> /// <param name="key">The secret key.</param> /// <returns>System.Byte[].</returns> public byte[] Sign(byte[] message, byte[] key) { // Using Paseto Cryptography library return(Ed25519.Sign(message, key)); /* * Using NSec library * * var algo = new Ed25519(); * using (var k = Key.Import(algo, key, KeyBlobFormat.RawPrivateKey)) * { * return algo.Sign(k, message); * } */ // Using Sodium Core library //return PublicKeyAuth.SignDetached(message, key); }
private void SetupLocalAsNode() { IEnumerable <NodeRecord> nodes = DataAccessService.Instance.GetAllNodes(); if (!nodes.Any(n => "127.0.0.1".Equals(new IPAddress(n.IPAddress).ToString()))) { byte[] seed = CryptoHelper.GetRandomSeed(); byte[] publicKey = Ed25519.PublicKeyFromSeed(seed); IKey key = _identityKeyProvider.GetKey(publicKey); DataAccessService.Instance.AddNode(key, NodeRole.TransactionsRegistrationLayer, IPAddress.Parse("127.0.0.1")); DataAccessService.Instance.AddNode(key, NodeRole.StorageLayer, IPAddress.Parse("127.0.0.1")); DataAccessService.Instance.AddNode(key, NodeRole.SynchronizationLayer, IPAddress.Parse("127.0.0.1")); Console.WriteLine($"Please copy carefully aside seed below for providing as input argument to Node executable:"); Console.WriteLine(seed.ToHexString()); } }
public void KeyExchangeSegments() { var seed = new byte[32].Pad(); var publicEdwards = new byte[32].Pad(); var privateEdwards = new byte[64].Pad(); Ed25519.KeyPairFromSeed(publicEdwards, privateEdwards, seed); var sharedEdwards = new byte[32].Pad(); Ed25519.KeyExchange(sharedEdwards, publicEdwards, privateEdwards); var privateMontgomery = Sha512.Hash(seed.UnPad()).Take(32).ToArray(); var publicMontgomery = MontgomeryCurve25519.GetPublicKey(privateMontgomery); var sharedMontgomery = MontgomeryCurve25519.KeyExchange(publicMontgomery, privateMontgomery); TestHelpers.AssertEqualBytes(sharedMontgomery, sharedEdwards.UnPad()); }
public static (PublicKey Public, byte[] Private) GetPublicPrivateKey(string seed, uint index) { var seedBytes = HexStringToByteArray(seed); var blake = Blake2Sharp.Blake2B.Create(new Blake2Sharp.Blake2BConfig() { OutputSizeInBytes = 32 }); blake.Init(); blake.Update(seedBytes); blake.Update(BitConverter.IsLittleEndian ? BitConverter.GetBytes(index).Reverse().ToArray() : BitConverter.GetBytes(index)); var privateKey = blake.Finish(); var publicKey = Ed25519.PublicKey(privateKey); return(new PublicKey(publicKey), privateKey); }
public void Sign(Ed25519.Algorithm algorithm, byte[] ctx, byte[] msg, int msgOff, int msgLen, byte[] sig, int sigOff) { Ed25519PublicKeyParameters publicKey = GeneratePublicKey(); byte[] pk = new byte[Ed25519.PublicKeySize]; publicKey.Encode(pk, 0); switch (algorithm) { case Ed25519.Algorithm.Ed25519: { if (null != ctx) { throw new ArgumentException("ctx"); } Ed25519.Sign(data, 0, pk, 0, msg, msgOff, msgLen, sig, sigOff); break; } case Ed25519.Algorithm.Ed25519ctx: { Ed25519.Sign(data, 0, pk, 0, ctx, msg, msgOff, msgLen, sig, sigOff); break; } case Ed25519.Algorithm.Ed25519ph: { if (Ed25519.PrehashSize != msgLen) { throw new ArgumentException("msgLen"); } Ed25519.SignPrehash(data, 0, pk, 0, ctx, msg, msgOff, sig, sigOff); break; } default: { throw new ArgumentException("algorithm"); } } }