private static bool ValidateTransactionIns(TransactionIn txIn, Transaction transaction, UnspentTransactionOut[] unspentTxsOut) { var referencedUTxOut = unspentTxsOut.FirstOrDefault((uTxO) => uTxO.TransactionOutId == txIn.TransactionOutId && uTxO.TransactionOutIndex == txIn.TransactionOutIndex); if (referencedUTxOut == null) { return(false); } var address = referencedUTxOut.Address; byte[] signature64 = Convert.FromBase64String(txIn.Signature); var publicKey = CngKey.Import(signature64, CngKeyBlobFormat.EccFullPublicBlob); using (ECDsaCng dsa = new ECDsaCng(publicKey)) { byte[] transactionIdBytes = Encoding.UTF8.GetBytes(transaction.Id); if (!dsa.VerifyData(transactionIdBytes, signature64)) { return(false); } } return(true); }
/// <summary> /// Verify and then parse the data in a JWT, this is the parsed version for increased efficiancy /// /// To create the verifier <see cref="Kalix.ApiCrypto.EC.ECDSACertificateParser.ParsePublicCertificate"/> /// </summary> /// <param name="token">The JWT to parse and verify</param> /// <param name="verificationCertificate">Public key certificate to verify the token with</param> /// <param name="verify">Whether to actually verify the token or not</param> /// <param name="headerJson">[Output] Header JSON string</param> /// <param name="payloadJson">[Output] Payload JSON string</param> /// <returns>Parsed object data</returns> public static T DecodeUsingECDSA <T>(string token, ECDsaCng verificationCertificate, bool verify, out string headerJson, out string payloadJson) { var parts = token.Split('.'); var header = parts[0]; var payload = parts[1]; headerJson = Encoding.UTF8.GetString(Base64UrlDecode(header)); if (verify) { var headerDetails = JsonConvert.DeserializeObject <IDictionary <string, string> >(headerJson); if (!headerDetails.ContainsKey("alg") || !headerDetails["alg"].StartsWith("ES")) { throw new SignatureVerificationException(string.Format("Unsupported signing algorithm.")); } if (verificationCertificate.KeySize.ToString() != headerDetails["alg"].Substring(2)) { throw new SignatureVerificationException(string.Format("Key size does not match.")); } var compare = Encoding.UTF8.GetBytes(string.Concat(header, ".", payload)); var signature = Base64UrlDecode(parts[2]); if (!verificationCertificate.VerifyData(compare, signature)) { throw new SignatureVerificationException(string.Format("Invalid signature.")); } } payloadJson = Encoding.UTF8.GetString(Base64UrlDecode(payload)); return(JsonConvert.DeserializeObject <T>(payloadJson)); }
public bool Verify(byte[] signature, byte[] securedInput, object key) { try { if (key is CngKey) { var publicKey = (CngKey)key; Ensure.BitSize(publicKey.KeySize, keySize, string.Format("EcdsaUsingSha algorithm expected key of size {0} bits, but was given {1} bits", keySize, publicKey.KeySize)); using (var signer = new ECDsaCng(publicKey)) { return(signer.VerifyData(securedInput, signature, Hash)); } } if (key is ECDsa) { var publicKey = (ECDsa)key; Ensure.BitSize(publicKey.KeySize, keySize, string.Format("EcdsaUsingSha algorithm expected key of size {0} bits, but was given {1} bits", keySize, publicKey.KeySize)); return(publicKey.VerifyData(securedInput, signature, Hash)); } throw new ArgumentException("EcdsaUsingSha algorithm expects key to be of either CngKey or ECDsa types."); } catch (CryptographicException e) { return(false); } }
/// <summary> /// 要验证签名是否真的来自于Alice,Bob使用Alice的公钥检查签名。包含公钥blob的字节数组可以用静态方法Import()导入CngKey对象。 /// 然后使用ECDsaCng类,调用VerifyData()方法来验证签名。 /// </summary> /// <param name="aliceData"></param> /// <param name="aliceSignature"></param> /// <param name="_alicePublicKeyBob"></param> /// <returns></returns> private static bool VerifySignature(byte[] data, byte[] signature, byte[] pubKey) { bool retValue = false; using (CngKey key = CngKey.Import(pubKey, CngKeyBlobFormat.GenericPublicBlob)) using (var signingAlg = new ECDsaCng(key)) { #if NET46 retValue = signingAlg.VerifyData(data, signature); signingAlg.Clear(); #else retValue = signingAlg.VerifyData(data, signature, HashAlgorithmName.SHA512); #endif } return(retValue); }
public static bool VerifySignatureECDsa(byte[] message, byte[] signature, byte[] pubkey, ECDsaCurve curve) { NetCrypto.ECCurve usedCurve = NetCrypto.ECCurve.NamedCurves.nistP256; switch (curve) { case ECDsaCurve.Secp256r1: // default break; case ECDsaCurve.Secp256k1: var oid = NetCrypto.Oid.FromFriendlyName("secP256k1", NetCrypto.OidGroup.PublicKeyAlgorithm); usedCurve = NetCrypto.ECCurve.CreateFromOid(oid); break; } ; #if NET461 const int ECDSA_PUBLIC_P256_MAGIC = 0x31534345; pubkey = BitConverter.GetBytes(ECDSA_PUBLIC_P256_MAGIC).Concat(BitConverter.GetBytes(32)).Concat(pubkey).ToArray(); using (CngKey key = CngKey.Import(pubkey, CngKeyBlobFormat.EccPublicBlob)) using (ECDsaCng ecdsa = new ECDsaCng(key)) { return(ecdsa.VerifyData(message, signature, HashAlgorithmName.SHA256)); } #else using (var ecdsa = NetCrypto.ECDsa.Create(new NetCrypto.ECParameters { Curve = usedCurve, Q = ECPointDecode(pubkey, curve) })) { return(ecdsa.VerifyData(message, signature, NetCrypto.HashAlgorithmName.SHA256)); } #endif }
static void Main(string[] args) { byte[] data = new byte[] { 4, 114, 29, 223, 58, 3, 191, 170, 67, 128, 229, 33, 242, 178, 157, 150, 133, 25, 209, 139, 166, 69, 55, 26, 84, 48, 169, 165, 67, 232, 98, 9 }; byte[] x = new byte[] { 4, 114, 29, 223, 58, 3, 191, 170, 67, 128, 229, 33, 242, 178, 157, 150, 133, 25, 209, 139, 166, 69, 55, 26, 84, 48, 169, 165, 67, 232, 98, 9 }; byte[] y = new byte[] { 131, 116, 8, 14, 22, 150, 18, 75, 24, 181, 159, 78, 90, 51, 71, 159, 214, 186, 250, 47, 207, 246, 142, 127, 54, 183, 72, 72, 253, 21, 88, 53 }; byte[] d = new byte[] { 42, 148, 231, 48, 225, 196, 166, 201, 23, 190, 229, 199, 20, 39, 226, 70, 209, 148, 29, 70, 125, 14, 174, 66, 9, 198, 80, 251, 95, 107, 98, 206 }; ECParameters ecp = new ECParameters(); ecp.Curve = ECCurve.NamedCurves.nistP256; ecp.Q.X = x; ecp.Q.Y = y; ecp.D = d; ECDsaCng ecDsaCng = new ECDsaCng(); ecDsaCng.ImportParameters(ecp); CngKey cngKey = ecDsaCng.Key; ECDsaCng eCDsaCng = new ECDsaCng(cngKey); byte[] sign = eCDsaCng.SignData(data); Console.WriteLine(eCDsaCng.VerifyData(data, sign)); Console.ReadKey(); }
private byte[] Find_Public_Key(string name) { if (File.Exists(PK_store_path + "\\" + current_user + "\\" + name + ".pk")) { using (BinaryReader reader = new BinaryReader(File.Open(PK_store_path + "\\" + current_user + "\\" + name + ".pk", FileMode.Open))) { int name_len = reader.ReadInt32(); int blob_len = reader.ReadInt32(); string readed_name = Encoding.Default.GetString(reader.ReadBytes(name_len)); byte[] readed_blob = reader.ReadBytes(blob_len); byte[] readed_sign = reader.ReadBytes((int)(reader.BaseStream.Length - reader.BaseStream.Position)); if (name == readed_name && ecdsaCng.VerifyData(readed_blob, readed_sign, HashAlgorithmName.SHA256)) { return(readed_blob); } else { throw new Exception("bad"); } } } else { return(null); } }
public static void TestVerify521_EcdhKey() { byte[] keyBlob = (byte[])TestData.s_ECDsa521KeyBlob.Clone(); // Rewrite the dwMagic value to be ECDH // ECDSA prefix: 45 43 53 36 // ECDH prefix : 45 43 4b 36 keyBlob[2] = 0x4b; using (CngKey ecdh521 = CngKey.Import(keyBlob, CngKeyBlobFormat.EccPrivateBlob)) { // Preconditions: Assert.Equal(CngAlgorithmGroup.ECDiffieHellman, ecdh521.AlgorithmGroup); Assert.Equal(CngAlgorithm.ECDiffieHellmanP521, ecdh521.Algorithm); using (ECDsa ecdsaFromEcdsaKey = new ECDsaCng(TestData.s_ECDsa521Key)) using (ECDsa ecdsaFromEcdhKey = new ECDsaCng(ecdh521)) { byte[] ecdhKeySignature = ecdsaFromEcdhKey.SignData(keyBlob, HashAlgorithmName.SHA512); byte[] ecdsaKeySignature = ecdsaFromEcdsaKey.SignData(keyBlob, HashAlgorithmName.SHA512); Assert.True( ecdsaFromEcdhKey.VerifyData(keyBlob, ecdsaKeySignature, HashAlgorithmName.SHA512), "ECDsaCng(ECDHKey) validates ECDsaCng(ECDsaKey)"); Assert.True( ecdsaFromEcdsaKey.VerifyData(keyBlob, ecdhKeySignature, HashAlgorithmName.SHA512), "ECDsaCng(ECDsaKey) validates ECDsaCng(ECDHKey)"); } } }
/// <inheritdoc /> protected internal override bool VerifySignature(byte[] data, byte[] signature) { using (var cng = new ECDsaCng(this.key)) { return(cng.VerifyData(data, signature)); } }
private static void ReadOpenSSLKeyTest() { //待签名数据 byte[] data = Encoding.UTF8.GetBytes("Hello World."); //读取OpenSSL产生的椭圆私钥和公钥 CngKey privateKey = OpenSSLKeyECC.GetPrivateKey(@"..\..\TestData\prime256v1.key"); CngKey pubKey = OpenSSLKeyECC.GetPublicKey(@"..\..\TestData\prime256v1.pub"); //使用私钥签名 ECDsaCng dsa1 = new ECDsaCng(privateKey); dsa1.HashAlgorithm = CngAlgorithm.Sha256; byte[] signature = dsa1.SignData(data); //使用公钥验签 ECDsaCng dsa2 = new ECDsaCng(pubKey); dsa2.HashAlgorithm = CngAlgorithm.Sha256; bool bVerified = dsa2.VerifyData(data, signature); if (bVerified) { Console.WriteLine("Verified"); } else { Console.WriteLine("Not verified"); } }
/// <summary>デジタル署名を検証する</summary> /// <param name="data">デジタル署名を行なった対象データ</param> /// <param name="sign">対象データに対してデジタル署名したデジタル署名部分のデータ</param> /// <returns>検証結果( true:検証成功, false:検証失敗 )</returns> public override bool Verify(byte[] data, byte[] sign) { ECDsaCng aa = new ECDsaCng(CngKey.Import( this._publicKey, CngKeyBlobFormat.EccPublicBlob)); return(aa.VerifyData(data, sign)); }
public bool Verify(byte[] message, byte[] publicKey, byte[] signature) { using (var ecdsa = new ECDsaCng(CngKey.Import(publicKey, CngKeyBlobFormat.EccPublicBlob))) { return(ecdsa.VerifyData(message, signature, HashAlgorithmName.SHA1)); } }
public static bool Veryify(byte[] data, byte[] signature) { using (ECDsaCng ecsdKey = new ECDsaCng(CngKey.Import(_key, CngKeyBlobFormat.EccPublicBlob))) { return(ecsdKey.VerifyData(data, signature)); } }
public static bool VerifySignature(string Message, string Signature, string PublicKey) { try { byte[] publicKey = ConvertToBytes(PublicKey); byte[] message = ConvertToBytes(Message); byte[] signature = ConvertToBytes(Signature); bool verified = false; using (CngKey importedKey = CngKey.Import(publicKey, CngKeyBlobFormat.EccPublicBlob)) { using (ECDsaCng importedDSA = new ECDsaCng(importedKey)) { verified = importedDSA.VerifyData(message, signature); } } return(verified); } catch { return(false); } }
static Boolean verifyECC(ECDsaCng key, Byte[] message, Byte[] signature, String hashAlgorithm) { switch (hashAlgorithm) { case "1.2.840.113549.2.5": key.HashAlgorithm = CngAlgorithm.MD5; break; case "1.3.14.3.2.26": key.HashAlgorithm = CngAlgorithm.Sha1; break; case "2.16.840.1.101.3.4.2.1": key.HashAlgorithm = CngAlgorithm.Sha256; break; case "2.16.840.1.101.3.4.2.2": key.HashAlgorithm = CngAlgorithm.Sha384; break; case "2.16.840.1.101.3.4.2.3": key.HashAlgorithm = CngAlgorithm.Sha512; break; } return(key.VerifyData(message, signature)); }
public bool VerifySignature(byte[] message, byte[] signature, byte[] pubkey) { if (pubkey.Length == 33 && (pubkey[0] == 0x02 || pubkey[0] == 0x03)) { try { pubkey = Cryptography.ECC.ECPoint.DecodePoint(pubkey, Cryptography.ECC.ECCurve.Secp256r1).EncodePoint(false).Skip(1).ToArray(); } catch { return(false); } } else if (pubkey.Length == 65 && pubkey[0] == 0x04) { pubkey = pubkey.Skip(1).ToArray(); } else if (pubkey.Length != 64) { throw new ArgumentException(); } const int ECDSA_PUBLIC_P256_MAGIC = 0x31534345; pubkey = BitConverter.GetBytes(ECDSA_PUBLIC_P256_MAGIC).Concat(BitConverter.GetBytes(32)).Concat(pubkey).ToArray(); using (CngKey key = CngKey.Import(pubkey, CngKeyBlobFormat.EccPublicBlob)) using (ECDsaCng ecdsa = new ECDsaCng(key)) { return(ecdsa.VerifyData(message, signature, HashAlgorithmName.SHA256)); } }
public bool VerifyWithEllipticCurve(string serializedKeys, string message, byte[] signature) { if (string.IsNullOrWhiteSpace(serializedKeys)) { throw new ArgumentNullException("serializedKeys"); } if (string.IsNullOrWhiteSpace(message)) { throw new ArgumentNullException("message"); } if (signature == null || !signature.Any()) { throw new ArgumentNullException("signature"); } var cngKey = _cngKeySerializer.DeserializeCngKeyWithPrivateKey(serializedKeys); var messageBytes = Encoding.UTF8.GetBytes(message); using (var ecsdaSignature = new ECDsaCng(cngKey)) { return(ecsdaSignature.VerifyData(messageBytes, 0, messageBytes.Length, signature)); // return ecsdaSignature.VerifyData(messageBytes, // signature); } }
public static Transaction FromBytes(byte[] data, bool partOfBlock = true) { var transaction = new Transaction(); transaction.originalData = data; Array.Copy(data, 0, transaction.source, 0, 72); Array.Copy(data, 72, transaction.target, 0, 20); transaction.amount = BitConverter.ToDouble(data, 92); transaction.timestamp = BitConverter.ToUInt32(data, 100); transaction.signature = new byte[data.Length - 104]; Array.Copy(data, 104, transaction.signature, 0, data.Length - 104); byte[] pubKeyHash = new byte[20]; using (SHA1 sha1 = SHA1.Create()) { pubKeyHash = sha1.ComputeHash(transaction.source); } if (transaction.amount > Program.Balances[pubKeyHash]) { Console.WriteLine("Bad amount - too much"); return(null); } if (transaction.amount <= 0) { Console.WriteLine("Bad amount - negative"); return(null); } var publicKey = CngKey.Import(transaction.source, CngKeyBlobFormat.EccPublicBlob); var publicKeyChecker = new ECDsaCng(publicKey); if (!publicKeyChecker.VerifyData(data, 0, 104, transaction.signature, HashAlgorithmName.SHA256)) { Console.WriteLine("Bad amount - bad signature"); return(null); } if (partOfBlock) { Program.Balances[pubKeyHash] -= transaction.amount; if (!Program.Balances.ContainsKey(transaction.target)) { Program.Balances[transaction.target] = 0; } Program.Balances[transaction.target] += transaction.amount; } if (Program.Swarm.Any(x => x.signature.SequenceEqual(transaction.signature))) { Program.Swarm.RemoveAll(x => x.signature.SequenceEqual(transaction.signature)); } return(transaction); }
/// <summary> /// Verifies a signature. /// </summary> /// <param name="data">The data that was signed.</param> /// <param name="signature">The signature data to be verified.</param> /// <returns></returns> public bool Verify(byte[] data, byte[] signature) { if (signature == null || signature.Length < 100) { return(false); // ECDsa signatures are typically length 132, although implementations can vary. } lock (dsa) return(dsa.VerifyData(data, signature)); }
private bool VerifySignedBytesAgainstSignature(CngKey publicKey, byte[] signedBytes, byte[] signature) { using (ECDsaCng verifier = new ECDsaCng(publicKey)) { verifier.HashAlgorithm = CngAlgorithm.Sha256; bool result = verifier.VerifyData(signedBytes, signature.FromAsn1Signature()); return(result); } }
private bool Verify(CngKey publicKey, byte[] signature, byte[] securedInput) { Ensure.BitSize(publicKey.KeySize, keySize, string.Format("EcdsaUsingSha algorithm expected key of size {0} bits, but was given {1} bits", keySize, publicKey.KeySize)); using (var signer = new ECDsaCng(publicKey)) { return(signer.VerifyData(securedInput, signature, Hash)); } }
public static void Main(string[] args) { if (args.Length != 2) { Console.WriteLine("Usage: ECCTest.exe ecdsaca.der ecdsakey.cng"); return; } X509Certificate2 cert = new X509Certificate2(args[0]); PublicKey publicKey = cert.PublicKey; ECDsaCng ecdsaPublicKey = GetECDSAFromPublicKey(publicKey); ecdsaPublicKey.HashAlgorithm = CngAlgorithm.Sha512; byte[] cngBlob = File.ReadAllBytes(args[1]); CngKey cngKey = CngKey.Import(cngBlob, CngKeyBlobFormat.GenericPrivateBlob, CngProvider.MicrosoftSoftwareKeyStorageProvider); ECDsaCng ecdsaPrivateKey = new ECDsaCng(cngKey); ecdsaPrivateKey.HashAlgorithm = CngAlgorithm.Sha512; byte[] data = new byte[256]; for (int i = 0; i < data.Length; i++) { data[i] = (byte)i; } byte[] signature = ecdsaPrivateKey.SignData(data); PrintBytes("signature", signature); Console.WriteLine("Signature verified: " + ecdsaPublicKey.VerifyData(data, signature)); ECDiffieHellmanBc alice = new ECDiffieHellmanBc(); ECDiffieHellmanCng bob = new ECDiffieHellmanCng(); byte[] aliceKey = alice.DeriveKeyMaterial(bob.PublicKey); byte[] bobKey = bob.DeriveKeyMaterial(alice.PublicKey); PrintBytes("alice key", aliceKey); PrintBytes("bob key", bobKey); Console.WriteLine("Running CMAC test"); byte[] keyBytes = new byte[24]; KeyParameter key = new KeyParameter(keyBytes); byte[] hashedData = new byte[31]; for (int i = 0; i < hashedData.Length; i++) { hashedData[i] = (byte)i; } CMac cmac = new CMac(new AesEngine(), 128); cmac.Init(key); cmac.BlockUpdate(hashedData, 0, hashedData.Length); byte[] hash = new byte[cmac.GetMacSize()]; cmac.DoFinal(hash, 0); PrintBytes("hash", hash); }
public bool Verify() { //Some optimisations can be made to keep dsa in cache. using (CngKey privateCngKey = CngKey.Import(PublicKey, CngKeyBlobFormat.EccPublicBlob)) using (ECDsaCng dsa = new ECDsaCng(privateCngKey)) { dsa.HashAlgorithm = CngAlgorithm.Sha256; return(dsa.VerifyData(Document, Signature)); } }
/// <summary> /// Verifies the ECDSA signature. /// </summary> /// <param name="data">The data.</param> /// <param name="signature">The signature.</param> /// <param name="pubKey">The public key key.</param> /// <param name="algorithm">The algorithm.</param> /// <returns>True if the signature is valid</returns> public static async Task <bool> VerifyAsync(byte[] data, byte[] signature, CngKey pubKey, CngAlgorithm algorithm) { using (ECDsaCng dsa = new ECDsaCng()) { dsa.HashAlgorithm = algorithm; // await is necessary here to avoid disposing of the dsa object // ReSharper disable once AccessToDisposedClosure return(await Task.Run(() => dsa.VerifyData(data, signature)).ConfigureAwait(false)); } }
internal void ReverifySignature(ECDsaCng senderDsa) { if (senderDsa.VerifyData(receivedRawMessage, receivedSignature)) { this.SignatureVerificationStatus = SignatureVerificationStatus.SignatureValid; } else { this.SignatureVerificationStatus = SignatureVerificationStatus.SignatureNotValid; } }
public bool Verify(string payload, byte[] signature, JsonWebKey jsonWebKey) { var plainBytes = ASCIIEncoding.ASCII.GetBytes(payload); using (var dsa = new ECDsaCng()) { dsa.HashAlgorithm = CngHashAlg; dsa.Import(jsonWebKey.Content); return(dsa.VerifyData(plainBytes, signature, HashAlg)); } }
private bool VerifySignaure(CngKey key, byte[] data, byte[] signature, byte[] pubkey) { bool retValue = false; using (ECDsaCng signingAlg = new ECDsaCng(key)) { retValue = signingAlg.VerifyData(data, signature); signingAlg.Clear(); } return(retValue); }
public bool Check(string source) { using (ECDsaCng ecsdKey = new ECDsaCng(CngKey.Import(key, CngKeyBlobFormat.EccPublicBlob))) { byte[] destData = new byte[source.Length / 2]; for (int i = 0; i < source.Length / 2; ++i) { destData[i] = Convert.ToByte(source.Substring(i * 2, 2), 16); } return(ecsdKey.VerifyData(TestDataBytes, destData)); } }
static bool VerifySignature(byte[] data, byte[] signature, byte[] pubKey) { bool retValue = false; using (CngKey key = CngKey.Import(pubKey, CngKeyBlobFormat.GenericPublicBlob)) using (var signingAlg = new ECDsaCng(key)) { retValue = signingAlg.VerifyData(data, signature); signingAlg.Clear(); } return(retValue); }
public bool VerifyFile(string path, string signPath) { StreamReader sr = new StreamReader(signPath); string keyBlockStr = sr.ReadToEnd(); sr.Close(); string[] keyBlockStrArray = keyBlockStr.Split(','); byte[] keyBlock = new byte[keyBlockStrArray.Length]; int i = 0; foreach (string item in keyBlockStrArray) { keyBlock[i] = byte.Parse(item); i++; } return(instance.VerifyData(new StreamReader(path).BaseStream, keyBlock)); }