public void EcdsaSelfTest() { using (var store = new Pkcs11X509Store(SoftHsm2Manager.LibraryPath, SoftHsm2Manager.PinProvider)) { Pkcs11X509Certificate cert1 = Helpers.GetCertificate(store, SoftHsm2Manager.Token1Label, SoftHsm2Manager.Token1TestUserEcdsaLabel); Pkcs11X509Certificate cert2 = Helpers.GetCertificate(store, SoftHsm2Manager.Token2Label, SoftHsm2Manager.Token2TestUserEcdsaLabel); foreach (var cert in new Pkcs11X509Certificate[] { cert1, cert2 }) { ECDsa p11PrivKey = cert.GetECDsaPrivateKey(); Assert.IsNotNull(p11PrivKey); ECDsa p11PubKey = cert.GetECDsaPublicKey(); Assert.IsNotNull(p11PubKey); foreach (HashAlgorithmName hashAlgName in _hashNames) { byte[] hash1 = Helpers.ComputeHash(_data1, hashAlgName); byte[] hash2 = Helpers.ComputeHash(_data2, hashAlgName); byte[] signature = p11PrivKey.SignHash(hash1); Assert.IsNotNull(signature); bool result1 = p11PubKey.VerifyHash(hash1, signature); Assert.IsTrue(result1); bool result2 = p11PubKey.VerifyHash(hash2, signature); Assert.IsFalse(result2); } } } }
private static void DoSignVerifyTests(int digestSize, ECDsa privateEcdsa, ECDsa publicEcdsa) { // Create pseudo-random hash. var rnd = new Random(0); var digest = new byte[digestSize]; rnd.NextBytes(digest); bool verified; // Check if private key can sign digest. var signature = privateEcdsa.SignHash(digest); // Check if private key can verify digest. verified = privateEcdsa.VerifyHash(digest, signature); Assert.True(verified); // Check if public key can verify digest. verified = publicEcdsa.VerifyHash(digest, signature); Assert.True(verified); signature[signature.Length - 1] ^= 1; // Check if private key can deny invalid digest. verified = privateEcdsa.VerifyHash(digest, signature); Assert.False(verified); // Check if public key can deny invalid digest. verified = publicEcdsa.VerifyHash(digest, signature); Assert.False(verified); }
public void EcdsaPlatformTest() { using (var store = new Pkcs11X509Store(SoftHsm2Manager.LibraryPath, SoftHsm2Manager.PinProvider)) { Pkcs11X509Certificate cert = Helpers.GetCertificate(store, SoftHsm2Manager.Token1Label, SoftHsm2Manager.Token1TestUserEcdsaLabel); ECDsa p11PrivKey = cert.GetECDsaPrivateKey(); Assert.IsNotNull(p11PrivKey); ECDsa p11PubKey = cert.GetECDsaPublicKey(); Assert.IsNotNull(p11PubKey); ECDsa cngKey = CryptoObjects.GetTestUserPlatformEcdsaProvider(); Assert.IsNotNull(cngKey); foreach (HashAlgorithmName hashAlgName in _hashNames) { byte[] hash1 = Helpers.ComputeHash(_data1, hashAlgName); byte[] hash2 = Helpers.ComputeHash(_data2, hashAlgName); byte[] p11Signature = p11PrivKey.SignHash(hash1); Assert.IsNotNull(p11Signature); bool result1 = cngKey.VerifyHash(hash1, p11Signature); Assert.IsTrue(result1); bool result2 = cngKey.VerifyHash(hash2, p11Signature); Assert.IsFalse(result2); byte[] cngSignature = cngKey.SignHash(hash1); Assert.IsNotNull(cngSignature); bool result3 = p11PubKey.VerifyHash(hash1, cngSignature); Assert.IsTrue(result3); bool result4 = p11PubKey.VerifyHash(hash2, cngSignature); Assert.IsFalse(result4); } } }
/// <inheritdoc /> public bool VerifySignature(string contentToSign, byte[] signature) { if (contentToSign == null) { throw new ArgumentNullException(nameof(contentToSign)); } if (signature == null) { throw new ArgumentNullException(nameof(signature)); } var signedBytes = Encoding.UTF8.GetBytes(contentToSign); HashAlgorithm hasher = null; try { hasher = _hasherPool.Get(); var hashedData = hasher.ComputeHash(signedBytes); return(_ecdsa.VerifyHash(hashedData, signature)); } finally { if (hasher != null) { _hasherPool.Return(hasher); } } }
/// <inheritdoc/> public override bool VerifyHash(byte[] hash, byte[] signature) { CheckDisposed(); ValidateKeyDigestCombination(KeySize, hash.Length); return(publicKey.VerifyHash(hash, signature)); }
internal static void Verify256(ECDsa e, bool expected) { byte[] sig = ("998791331eb2e1f4259297f5d9cb82fa20dec98e1cb0900e6b8f014a406c3d02cbdbf5238bde471c3155fc25565524301429" + "d8713dad9a67eb0a5c355e9e23dc").HexToByteArray(); bool verified = e.VerifyHash(ECDsaTestData.s_hashSha512, sig); Assert.Equal(expected, verified); }
protected override void UseAfterDispose(ECDsa ecdsa, byte[] data, byte[] sig) { base.UseAfterDispose(ecdsa, data, sig); byte[] hash = new byte[32]; Assert.Throws <ObjectDisposedException>(() => ecdsa.VerifyHash(hash, sig)); Assert.Throws <ObjectDisposedException>(() => ecdsa.SignHash(hash)); }
protected override void UseAfterDispose(ECDsa ecdsa, byte[] data, byte[] sig) { base.UseAfterDispose(ecdsa, data, sig); byte[] hash = new byte[32]; Assert.Throws <ObjectDisposedException>(() => ecdsa.VerifyHash(hash.AsSpan(), sig.AsSpan())); Assert.Throws <ObjectDisposedException>(() => ecdsa.SignData(hash.AsSpan(), HashAlgorithmName.SHA256)); Assert.Throws <ObjectDisposedException>(() => ecdsa.SignHash(hash.AsSpan())); }
public void SignVerify_InteroperableSameKeys_RoundTripsUnlessTampered(ECDsa ecdsa, HashAlgorithmName hashAlgorithm) { // large enough to make hashing work though multiple iterations and not a multiple of 4KB it uses. byte[] dataArray = new byte[33333]; byte[] dataArray2 = new byte[dataArray.Length + 2]; dataArray.CopyTo(dataArray2, 1); using HashAlgorithm halg = hashAlgorithm == HashAlgorithmName.MD5 ? MD5.Create() : hashAlgorithm == HashAlgorithmName.SHA1 ? SHA1.Create() : hashAlgorithm == HashAlgorithmName.SHA256 ? SHA256.Create() : hashAlgorithm == HashAlgorithmName.SHA384 ? SHA384.Create() : hashAlgorithm == HashAlgorithmName.SHA512 ? SHA512.Create() : throw new Exception("Hash algorithm not supported."); List <byte[]> signatures = new List <byte[]>(6); // Compute a signature using each of the SignData overloads. Then, verify it using each // of the VerifyData overloads, and VerifyHash overloads. // // Then, verify that VerifyHash fails if the data is tampered with. signatures.Add(SignData(ecdsa, dataArray, hashAlgorithm)); signatures.Add(ecdsa.SignHash(halg.ComputeHash(dataArray))); foreach (byte[] signature in signatures) { Assert.True(VerifyData(ecdsa, dataArray, signature, hashAlgorithm), "Verify 1"); Assert.True(ecdsa.VerifyHash(halg.ComputeHash(dataArray), signature), "Verify 4"); } int distinctSignatures = signatures.Distinct(new ByteArrayComparer()).Count(); Assert.True(distinctSignatures == signatures.Count, "Signing should be randomized"); foreach (byte[] signature in signatures) { signature[signature.Length - 1] ^= 0xFF; // flip some bits Assert.False(VerifyData(ecdsa, dataArray, signature, hashAlgorithm), "Verify Tampered 1"); Assert.False(ecdsa.VerifyHash(halg.ComputeHash(dataArray), signature), "Verify Tampered 4"); } }
public bool VerifySignature( ReadOnlySpan <byte> rgbHash, ReadOnlySpan <byte> rgbSignature, PgpHashAlgorithm hashAlgorithm) { var asnWriter = new AsnWriter(AsnEncodingRules.DER); using (var scope = asnWriter.PushSequence()) { asnWriter.WriteIntegerUnsigned(MPInteger.ReadInteger(rgbSignature, out int rConsumed)); asnWriter.WriteIntegerUnsigned(MPInteger.ReadInteger(rgbSignature.Slice(rConsumed), out var _)); } return(ecdsa.VerifyHash(rgbHash, asnWriter.Encode(), DSASignatureFormat.Rfc3279DerSequence)); }
public bool VerifySignature(string contentToSign, byte[] signature) { if (contentToSign == null) { throw new ArgumentNullException(nameof(contentToSign)); } if (signature == null) { throw new ArgumentNullException(nameof(signature)); } var signedBytes = Encoding.UTF8.GetBytes(contentToSign); using (var hasher = HashAlgorithmFactory.Create(HashAlgorithm)) { var hashedData = hasher.ComputeHash(signedBytes); return(_ecdsa.VerifyHash(hashedData, signature)); } }
public override bool VerifySignature(byte[] rgbHash, byte[] rgbSignature) { if (rgbHash == null) { throw new ArgumentNullException("rgbHash"); } if (m_key == null) { throw new Exception("Must initialize key before verifying a signature"); } if (m_hashAlgorithm == null) { throw new Exception("Must initialize hash algorithm before verifying a signature"); } bool valid = m_key.VerifyHash(rgbHash, rgbSignature); return(valid); }
public override VerifyResult Verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, CancellationToken cancellationToken) { // The JWK is not supported by this client. Send to the server. Argument.AssertNotNull(digest, nameof(digest)); Argument.AssertNotNull(signature, nameof(signature)); // The JWK is not supported by this client. Send to the server. if (KeyMaterial is null) { KeysEventSource.Singleton.AlgorithmNotSupported(nameof(Verify), _curve); return(null); } KeyCurveName algorithmCurve = algorithm.GetEcKeyCurveName(); if (_curve.KeySize != algorithmCurve.KeySize) { throw new ArgumentException($"Signature algorithm {algorithm} key size {algorithmCurve.KeySize} does not match underlying key size {_curve.KeySize}"); } if (_curve != algorithmCurve) { throw new ArgumentException($"Signature algorithm {algorithm} key curve name does not correspond to underlying key curve name {_curve}"); } using ECDsa ecdsa = KeyMaterial.ToECDsa(false, false); if (ecdsa is null) { return(null); } bool isValid = ecdsa.VerifyHash(digest, signature); return(new VerifyResult { Algorithm = algorithm, IsValid = isValid, KeyId = KeyMaterial.Id, }); }
private const string DefaultJwsHeader = "eyJhbGciOiJFUzI1NiJ9"; // Seite 42 der Spezifikation - Header Base64 URL encoded für R1 // Allgemein: https://openid.net/specs/draft-jones-json-web-signature-04.html#DefiningECDSA // // Spezifikation 3.1 Erstellung der JWS-Signatur (Sicherheitseinrichtung funktionsfähig) // "Wird die Signatur manuell erstellt (ohne Verwendung einer JWS-Bibliothek) muss darauf geachtet werden, dass der Signaturwert korrekt // formatiert ist. So verwendet z.B. Java ASN.1 für die Kodierung und die DER Darstellung für die Repräsentation des Signaturwerts. Der // JWS-Standard3 verlangt aber die einfache Konkatenierung der beiden Teilelemente des Signaturwertes R und S: R|S. Im Muster-Code ist // dies in den unten angegebenen Beispielen ersichtlich." public bool ValidateSignature(byte[] certificateBytes) { var cert = new X509Certificate2(certificateBytes); // https://stackoverflow.com/a/38235996/141927 using (ECDsa ecdsa = cert.GetECDsaPublicKey()) { if (ecdsa != null) { byte[] signature = Convert.FromBase64String(SignatureValue); if (64 != signature.Length) { return(false); } // Add: Check ob Cert zum Datum der Belegerstellung gültig war return(ecdsa.VerifyHash(GetJwsHash(), signature)); } } return(false); }
public static IActionResult Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, TraceWriter log) { // TODO: Proper error handling, proper monitoring (Application Insights) log.Info("C# HTTP trigger function processed a request."); string requestBody = new StreamReader(req.Body).ReadToEnd(); var data = JsonConvert.DeserializeObject <VerificationParameters>(requestBody); // Short-circuit out of here if signature is invalid anyways byte[] signature = Convert.FromBase64String(data.Signature); if (64 != signature.Length) { return(new BadRequestObjectResult("Signature is not 64 bytes in length")); } // TODO: A-Trust hardcoded, would be data.Authority switch // TODO: Here we would be adding the caching logic for the certificates (hash of authority & cert# for lookup) var certificateLookupResult = CertificateLookup.ATrust(data.CertificateNumber); // TODO: Assuming valid lookup, would need checking certificateLookupResult.Found var cert = new X509Certificate2(certificateLookupResult.CertificateBinary); // https://stackoverflow.com/a/38235996/141927 using (ECDsa ecdsa = cert.GetECDsaPublicKey()) { if (ecdsa != null) { bool valid = ecdsa.VerifyHash(Convert.FromBase64String(data.HashToVerify), signature); return((ActionResult) new OkObjectResult(valid)); } else { return(new NotFoundResult()); } } }
public static bool VerifyData(this byte[] data, byte[] sig, ECDsa key) { return(key.VerifyHash(SHA512.Create().ComputeHash(data), sig[1..]));
public void SignVerify_InteroperableSameKeys_RoundTripsUnlessTampered(ECDsa ecdsa, HashAlgorithmName hashAlgorithm) { byte[] data = Encoding.UTF8.GetBytes("something to repeat and sign"); // large enough to make hashing work though multiple iterations and not a multiple of 4KB it uses. byte[] dataArray = new byte[33333]; MemoryStream dataStream = new MemoryStream(dataArray, true); while (dataStream.Position < dataArray.Length - data.Length) { dataStream.Write(data, 0, data.Length); } dataStream.Position = 0; byte[] dataArray2 = new byte[dataArray.Length + 2]; dataArray.CopyTo(dataArray2, 1); ArraySegment <byte> dataSpan = new ArraySegment <byte>(dataArray2, 1, dataArray.Length); HashAlgorithm halg; if (hashAlgorithm == HashAlgorithmName.MD5) { halg = MD5.Create(); } else if (hashAlgorithm == HashAlgorithmName.SHA1) { halg = SHA1.Create(); } else if (hashAlgorithm == HashAlgorithmName.SHA256) { halg = SHA256.Create(); } else if (hashAlgorithm == HashAlgorithmName.SHA384) { halg = SHA384.Create(); } else if (hashAlgorithm == HashAlgorithmName.SHA512) { halg = SHA512.Create(); } else { throw new Exception("Hash algorithm not supported."); } List <byte[]> signatures = new List <byte[]>(6); // Compute a signature using each of the SignData overloads. Then, verify it using each // of the VerifyData overloads, and VerifyHash overloads. // // Then, verify that VerifyHash fails if the data is tampered with. signatures.Add(ecdsa.SignData(dataArray, hashAlgorithm)); signatures.Add(ecdsa.SignData(dataSpan.Array, dataSpan.Offset, dataSpan.Count, hashAlgorithm)); signatures.Add(ecdsa.SignData(dataStream, hashAlgorithm)); dataStream.Position = 0; signatures.Add(ecdsa.SignHash(halg.ComputeHash(dataArray))); signatures.Add(ecdsa.SignHash(halg.ComputeHash(dataSpan.Array, dataSpan.Offset, dataSpan.Count))); signatures.Add(ecdsa.SignHash(halg.ComputeHash(dataStream))); dataStream.Position = 0; foreach (byte[] signature in signatures) { Assert.True(ecdsa.VerifyData(dataArray, signature, hashAlgorithm), "Verify 1"); Assert.True(ecdsa.VerifyData(dataSpan.Array, dataSpan.Offset, dataSpan.Count, signature, hashAlgorithm), "Verify 2"); Assert.True(ecdsa.VerifyData(dataStream, signature, hashAlgorithm), "Verify 3"); Assert.True(dataStream.Position == dataArray.Length, "Check stream read 3A"); dataStream.Position = 0; Assert.True(ecdsa.VerifyHash(halg.ComputeHash(dataArray), signature), "Verify 4"); Assert.True(ecdsa.VerifyHash(halg.ComputeHash(dataSpan.Array, dataSpan.Offset, dataSpan.Count), signature), "Verify 5"); Assert.True(ecdsa.VerifyHash(halg.ComputeHash(dataStream), signature), "Verify 6"); Assert.True(dataStream.Position == dataArray.Length, "Check stream read 6A"); dataStream.Position = 0; } int distinctSignatures = signatures.Distinct(new ByteArrayComparer()).Count(); Assert.True(distinctSignatures == signatures.Count, "Signing should be randomized"); foreach (byte[] signature in signatures) { signature[signature.Length - 1] ^= 0xFF; // flip some bits Assert.False(ecdsa.VerifyData(dataArray, signature, hashAlgorithm), "Verify Tampered 1"); Assert.False(ecdsa.VerifyData(dataSpan.Array, dataSpan.Offset, dataSpan.Count, signature, hashAlgorithm), "Verify Tampered 2"); Assert.False(ecdsa.VerifyData(dataStream, signature, hashAlgorithm), "Verify Tampered 3"); Assert.True(dataStream.Position == dataArray.Length, "Check stream read 3B"); dataStream.Position = 0; Assert.False(ecdsa.VerifyHash(halg.ComputeHash(dataArray), signature), "Verify Tampered 4"); Assert.False(ecdsa.VerifyHash(halg.ComputeHash(dataSpan.Array, dataSpan.Offset, dataSpan.Count), signature), "Verify Tampered 5"); Assert.False(ecdsa.VerifyHash(halg.ComputeHash(dataStream), signature), "Verify Tampered 6"); Assert.True(dataStream.Position == dataArray.Length, "Check stream read 6B"); dataStream.Position = 0; } }
public void VerifyHash_NullSignature_ThrowsArgumentNullException(ECDsa ecdsa) { AssertExtensions.Throws <ArgumentNullException>( "signature", () => ecdsa.VerifyHash(new byte[0], null)); }
public void VerifyHash_NullHash_ThrowsArgumentNullException(ECDsa ecdsa) { AssertExtensions.Throws <ArgumentNullException>( "hash", () => ecdsa.VerifyHash(null, null)); }
public void VerifyHash_InvalidArguments_Throws(ECDsa ecdsa) { AssertExtensions.Throws <ArgumentNullException>("hash", () => ecdsa.VerifyHash(null, null)); AssertExtensions.Throws <ArgumentNullException>("signature", () => ecdsa.VerifyHash(new byte[0], null)); }
private bool VerifyWithECDsa(byte[] bytes, byte[] signature) { return(ECDsa.VerifyHash(HashAlgorithm.ComputeHash(bytes), signature)); }
public override bool VerifyHash(byte[] hash, byte[] signature) => _impl.VerifyHash(hash, signature);
protected override bool VerifyHash(ECDsa ecdsa, byte[] hash, int offset, int count, byte[] signature) => ecdsa.VerifyHash(new ReadOnlySpan <byte>(hash, offset, count), signature);
public bool Verify(byte[] digest, byte[] signature) { return(_key.VerifyHash(digest, signature)); }
protected static bool VerifyData(ECDsa key, byte[] signature, params byte[][] data) { byte[] hash = HashData(HashAlgorithmName.SHA256, data); return(key.VerifyHash(hash, signature)); }
/// <summary> /// Verifies if a hash corrersponds with the signatrue of the current key. /// </summary> /// <param name="rgbHash">The (raw) hash value</param> /// <param name="rgbSignature">The signature value</param> /// <returns></returns> public override bool VerifySignature(byte[] rgbHash, byte[] rgbSignature) { return(_key.VerifyHash(rgbHash, rgbSignature)); }
public bool VerifyDigest(byte[] digest, byte[] signature, HashAlgorithmName pkcsAlgorithm) => _algorithm.VerifyHash(digest, signature);