public virtual byte[] SignData(byte[] data, HashAlgorithmName hashAlgorithm) { if (data == null) throw new ArgumentNullException("data"); return SignData(data, 0, data.Length, hashAlgorithm); }
/// <summary> /// Create an <see cref="IncrementalHash"/> for the algorithm specified by <paramref name="hashAlgorithm"/>. /// </summary> /// <param name="hashAlgorithm">The name of the hash algorithm to perform.</param> /// <returns> /// An <see cref="IncrementalHash"/> instance ready to compute the hash algorithm specified /// by <paramref name="hashAlgorithm"/>. /// </returns> /// <exception cref="ArgumentException"> /// <paramref name="hashAlgorithm"/>.<see cref="HashAlgorithmName.Name"/> is <c>null</c>, or /// the empty string. /// </exception> /// <exception cref="CryptographicException"><paramref name="hashAlgorithm"/> is not a known hash algorithm.</exception> public static IncrementalHash CreateHash(HashAlgorithmName hashAlgorithm) { if (string.IsNullOrEmpty(hashAlgorithm.Name)) throw new ArgumentException(SR.Cryptography_HashAlgorithmNameNullOrEmpty, nameof(hashAlgorithm)); return new IncrementalHash(hashAlgorithm, GetHashAlgorithm(hashAlgorithm)); }
public bool VerifyData(byte[] data, byte[] signature, HashAlgorithmName hashAlgorithm) { if (data == null) throw new ArgumentNullException("data"); return VerifyData(data, 0, data.Length, signature, hashAlgorithm); }
public static void VerifyIncrementalHash(HashAlgorithm referenceAlgorithm, HashAlgorithmName hashAlgorithm) { using (referenceAlgorithm) using (IncrementalHash incrementalHash = IncrementalHash.CreateHash(hashAlgorithm)) { VerifyIncrementalResult(referenceAlgorithm, incrementalHash); } }
public virtual byte[] SignData(Stream data, HashAlgorithmName hashAlgorithm) { if (data == null) { throw new ArgumentNullException(nameof(data)); } if (String.IsNullOrEmpty(hashAlgorithm.Name)) { throw HashAlgorithmNameNullOrEmpty(); } byte[] hash = HashData(data, hashAlgorithm); return CreateSignature(hash); }
/// <summary> /// Derive key material using the formula HASH(secretPrepend || x || secretAppend) where x is the computed /// result of the EC Diffie-Hellman algorithm. /// </summary> /// <param name="otherPartyPublicKey">The public key of the party with which to derive a mutual secret.</param> /// <param name="hashAlgorithm">The identifier for the hash algorithm to use.</param> /// <param name="secretPrepend">A value to prepend to the derived secret before hashing. A <c>null</c> value is treated as an empty array.</param> /// <param name="secretAppend">A value to append to the derived secret before hashing. A <c>null</c> value is treated as an empty array.</param> /// <returns>A hashed output suitable for key material</returns> /// <exception cref="ArgumentException"><paramref name="otherPartyPublicKey"/> is over a different curve than this key</exception> public virtual byte[] DeriveKeyFromHash( ECDiffieHellmanPublicKey otherPartyPublicKey, HashAlgorithmName hashAlgorithm, byte[] secretPrepend, byte[] secretAppend) { throw DerivedClassMustOverride(); }
private IncrementalHash(HashAlgorithmName name, HashAlgorithm hash) { Debug.Assert(name != null); Debug.Assert(!string.IsNullOrEmpty(name.Name)); Debug.Assert(hash != null); _algorithmName = name; _hash = hash; }
public byte[] SignData(byte[] data, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { if (data == null) { throw new ArgumentNullException("data"); } return SignData(data, 0, data.Length, hashAlgorithm, padding); }
public virtual bool VerifyData(Stream data, byte[] signature, HashAlgorithmName hashAlgorithm) { if (data == null) { throw new ArgumentNullException(nameof(data)); } if (signature == null) { throw new ArgumentNullException(nameof(signature)); } if (String.IsNullOrEmpty(hashAlgorithm.Name)) { throw HashAlgorithmNameNullOrEmpty(); } byte[] hash = HashData(data, hashAlgorithm); return VerifySignature(hash, signature); }
public virtual byte[] SignData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm) { if (data == null) { throw new ArgumentNullException("data"); } if (offset < 0 || offset > data.Length) { throw new ArgumentOutOfRangeException("offset"); } if (count < 0 || count > data.Length - offset) { throw new ArgumentOutOfRangeException("count"); } if (String.IsNullOrEmpty(hashAlgorithm.Name)) { throw HashAlgorithmNameNullOrEmpty(); } byte[] hash = HashData(data, offset, count, hashAlgorithm); return SignHash(hash); }
protected override byte[] HashData(Stream data, HashAlgorithmName hashAlgorithm) { // We're sealed and the base should have checked these already. Debug.Assert(data != null); Debug.Assert(!string.IsNullOrEmpty(hashAlgorithm.Name)); HashAlgorithm hasher = GetHasher(hashAlgorithm); byte[] hash = hasher.ComputeHash(data); return hash; }
public virtual byte[] SignData(Stream data, HashAlgorithmName hashAlgorithm) { if (data == null) throw new ArgumentNullException("data"); if (string.IsNullOrEmpty(hashAlgorithm.Name)) throw new ArgumentException(SR.Cryptography_HashAlgorithmNameNullOrEmpty, "hashAlgorithm"); byte[] hash = HashData(data, hashAlgorithm); return SignHash(hash); }
public static void VerifyIncrementalHMAC(HMAC referenceAlgorithm, HashAlgorithmName hashAlgorithm) { using (referenceAlgorithm) using (IncrementalHash incrementalHash = IncrementalHash.CreateHMAC(hashAlgorithm, s_hmacKey)) { referenceAlgorithm.Key = s_hmacKey; VerifyIncrementalResult(referenceAlgorithm, incrementalHash); } }
public virtual bool VerifyData(byte[] data, int offset, int count, byte[] signature, HashAlgorithmName hashAlgorithm) { if (data == null) { throw new ArgumentNullException(nameof(data)); } if (offset < 0 || offset > data.Length) { throw new ArgumentOutOfRangeException(nameof(offset)); } if (count < 0 || count > data.Length - offset) { throw new ArgumentOutOfRangeException(nameof(count)); } if (signature == null) { throw new ArgumentNullException(nameof(signature)); } if (String.IsNullOrEmpty(hashAlgorithm.Name)) { throw HashAlgorithmNameNullOrEmpty(); } byte[] hash = HashData(data, offset, count, hashAlgorithm); return VerifySignature(hash, signature); }
public static HashAlgorithm GetHashAlgorithm(HashAlgorithmName name) { switch (name) { case HashAlgorithmName.MD5: return new MD5CryptoServiceProvider(); case HashAlgorithmName.SHA1: return new SHA1Managed(); } throw new Exception("Unknown hash algorithm!"); }
public bool VerifyData(Stream data, byte[] signature, HashAlgorithmName hashAlgorithm) { if (data == null) throw new ArgumentNullException("data"); if (signature == null) throw new ArgumentNullException("signature"); if (string.IsNullOrEmpty(hashAlgorithm.Name)) throw new ArgumentException(SR.Cryptography_HashAlgorithmNameNullOrEmpty, "hashAlgorithm"); byte[] hash = HashData(data, hashAlgorithm); return VerifyHash(hash, signature); }
protected override byte[] HashData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm) { // we're sealed and the base should have checked this already. Debug.Assert(data != null); Debug.Assert(offset >= 0 && offset <= data.Length); Debug.Assert(count >= 0 && count <= data.Length); Debug.Assert(!string.IsNullOrEmpty(hashAlgorithm.Name)); HashAlgorithm hasher = GetHasher(hashAlgorithm); byte[] hash = hasher.ComputeHash(data, offset, count); return hash; }
public virtual byte[] SignData(Stream data, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { if (data == null) throw new ArgumentNullException("data"); if (string.IsNullOrEmpty(hashAlgorithm.Name)) throw HashAlgorithmNameNullOrEmpty(); if (padding == null) throw new ArgumentNullException("padding"); byte[] hash = HashData(data, hashAlgorithm); return SignHash(hash, hashAlgorithm, padding); }
public virtual byte[] SignData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm) { if (data == null) throw new ArgumentNullException("data"); if (offset < 0 || offset > data.Length) throw new ArgumentOutOfRangeException("offset"); if (count < 0 || count > data.Length - offset) throw new ArgumentOutOfRangeException("count"); if (string.IsNullOrEmpty(hashAlgorithm.Name)) throw new ArgumentException(SR.Cryptography_HashAlgorithmNameNullOrEmpty, "hashAlgorithm"); byte[] hash = HashData(data, offset, count, hashAlgorithm); return SignHash(hash); }
private static void TestSignVerifyDataRoundTrip(byte[] message, HashAlgorithmName hashAlgorithm, RSASignaturePadding paddingMode, int expectedSignatureLength) { using (RSA rsa = new RSACng()) { byte[] signature = rsa.SignData(message, hashAlgorithm, paddingMode); // RSACng.SignHash() is intentionally non-deterministic so we can verify that we got back a signature of the right length // but nothing about the contents. Assert.Equal(expectedSignatureLength, signature.Length); bool verified = rsa.VerifyData(message, signature, hashAlgorithm, paddingMode); Assert.True(verified); } }
internal static IncrementalHash CreateHash(HashAlgorithmName hashAlgorithmName) { switch (hashAlgorithmName) { default: case HashAlgorithmName.SHA1: return new IncrementalHash{ HashAlgorithm = SHA1.Create() }; case HashAlgorithmName.SHA256: return new IncrementalHash{ HashAlgorithm = SHA256.Create() }; case HashAlgorithmName.SHA512: return new IncrementalHash{ HashAlgorithm = SHA512.Create() }; case HashAlgorithmName.MD5: return new IncrementalHash{ HashAlgorithm = MD5.Create() }; } }
internal static IncrementalHash CreateHMAC(HashAlgorithmName hashAlgorithmName, byte[] key) { switch (hashAlgorithmName) { default: case HashAlgorithmName.SHA1: return new IncrementalHash{ HashAlgorithm = new HMACSHA1(key) }; case HashAlgorithmName.SHA256: return new IncrementalHash{ HashAlgorithm = new HMACSHA256(key) }; case HashAlgorithmName.SHA512: return new IncrementalHash{ HashAlgorithm = new HMACSHA512(key) }; case HashAlgorithmName.MD5: return new IncrementalHash{ HashAlgorithm = new HMACMD5(key) }; } }
public virtual bool VerifyData(byte[] data, int offset, int count, byte[] signature, HashAlgorithmName hashAlgorithm) { if (data == null) throw new ArgumentNullException(nameof(data)); if (offset < 0 || offset > data.Length) throw new ArgumentOutOfRangeException(nameof(offset)); if (count < 0 || count > data.Length - offset) throw new ArgumentOutOfRangeException(nameof(count)); if (signature == null) throw new ArgumentNullException(nameof(signature)); if (string.IsNullOrEmpty(hashAlgorithm.Name)) throw new ArgumentException(SR.Cryptography_HashAlgorithmNameNullOrEmpty, nameof(hashAlgorithm)); byte[] hash = HashData(data, offset, count, hashAlgorithm); return VerifyHash(hash, signature); }
public override byte[] SignHash(byte[] hash, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { if (hashAlgorithm != HashAlgorithmName.SHA256) { throw new ArgumentException( $"Unsupported HashAlgorithmName '{hashAlgorithm}', only SHA256 supported.", nameof(hashAlgorithm)); } if (padding != RSASignaturePadding.Pkcs1) { throw new ArgumentException( $"Unsupported RSASignaturePadding '{padding}', only Pkcs1 supported.", nameof(padding)); } var signer = new RsaDigestSigner(new NullDigest(), NistObjectIdentifiers.IdSha256); signer.Init(true, _parameters); signer.BlockUpdate(hash, 0, hash.Length); return signer.GenerateSignature(); }
/// <summary> /// Creates an RSA PKCS#1 v1.5 signature of a hash algorithm for the stream. /// </summary> private static byte[] RsaPkcs15_Sign( ArraySegment<byte> dataToSign, X509Certificate2 signingCertificate, HashAlgorithmName algorithm) { // extract the private key. using (RSA rsa = signingCertificate.GetRSAPrivateKey()) { if (rsa == null) { throw ServiceResultException.Create(StatusCodes.BadSecurityChecksFailed, "No private key for certificate."); } // create the signature. return rsa.SignData(dataToSign.Array, dataToSign.Offset, dataToSign.Count, algorithm, RSASignaturePadding.Pkcs1); } }
/// <summary> /// Get HashAlgorithm with specify name /// </summary> /// <param name="name">name of hash algorithm</param> /// <returns></returns> private HashAlgorithm GetHashAlgorithm(HashAlgorithmName name) { switch (name) { case HashAlgorithmName.MD5: return new MD5CryptoServiceProvider(); case HashAlgorithmName.SHA1: return new SHA1Managed(); case HashAlgorithmName.SHA256: return new SHA256Managed(); case HashAlgorithmName.SHA384: return new SHA384Managed(); case HashAlgorithmName.SHA512: return new SHA512Managed(); } throw new CryptographicException("Unknown hash algorithm!"); }
/// <summary> /// Get the ALG_ID from the given HashAlgorithmName /// </summary> internal static Interop.BCrypt.ECC_CURVE_ALG_ID_ENUM GetHashAlgorithmId(HashAlgorithmName? name) { if (name.HasValue == false || string.IsNullOrEmpty(name.Value.Name)) { return Interop.BCrypt.ECC_CURVE_ALG_ID_ENUM.BCRYPT_NO_CURVE_GENERATION_ALG_ID; } CRYPT_OID_INFO oid = Interop.Crypt32.FindOidInfo( CryptOidInfoKeyType.CRYPT_OID_INFO_NAME_KEY, name.Value.Name, OidGroup.HashAlgorithm, false); if (oid.AlgId == -1) { throw new CryptographicException(SR.Cryptography_UnknownHashAlgorithm, name.Value.Name); } return (Interop.BCrypt.ECC_CURVE_ALG_ID_ENUM)oid.AlgId; }
public virtual byte[] SignData( byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { if (data == null) throw new ArgumentNullException("data"); if (offset < 0 || offset > data.Length) throw new ArgumentOutOfRangeException("offset"); if (count < 0 || count > data.Length - offset) throw new ArgumentOutOfRangeException("count"); if (string.IsNullOrEmpty(hashAlgorithm.Name)) throw HashAlgorithmNameNullOrEmpty(); if (padding == null) throw new ArgumentNullException("padding"); byte[] hash = HashData(data, offset, count, hashAlgorithm); return SignHash(hash, hashAlgorithm, padding); }
protected CacheKey(IDictionary<string, object> key, Type type, string operation, OperationReturnType returnType, bool sorted, HashAlgorithmName hashAlgorithm = HashAlgorithmName.Default) { var reflectedType = Reflector.GetReflectedType(type); var typeName = reflectedType.IsBusinessObject && reflectedType.InterfaceTypeName != null ? reflectedType.InterfaceTypeName : reflectedType.FullTypeName; _hashAlgorithm = hashAlgorithm == HashAlgorithmName.Default ? ObjectFactory.Configuration.DefaultHashAlgorithm : hashAlgorithm; if (_hashAlgorithm == HashAlgorithmName.Native || _hashAlgorithm == HashAlgorithmName.None) { var keyValue = (sorted ? key.Select(k => string.Format("{0}={1}", k.Key, Uri.EscapeDataString(Convert.ToString(k.Value)))) : key.OrderBy(k => k.Key).Select(k => string.Format("{0}={1}", k.Key, Uri.EscapeDataString(Convert.ToString(k.Value))))).ToDelimitedString("&"); if (!string.IsNullOrEmpty(operation)) { _value = string.Concat(typeName, "->", operation, "[", returnType, "]", "::", keyValue); } else { _value = string.Concat(typeName, "::", keyValue); } _data = _value.ToByteArray(); } else { Func<KeyValuePair<string, object>, IEnumerable<byte>> func = k => BitConverter.GetBytes(k.Key.GetHashCode()).Append((byte)'=').Concat(BitConverter.GetBytes(k.Value.GetHashCode())).Append((byte)'&'); var keyValue = (sorted ? key.Select(func) : key.OrderBy(k => k.Key).Select(func)).Flatten().ToArray(); if (!string.IsNullOrEmpty(operation)) { _data = new byte[4 + 4 + 1 + keyValue.Length]; Buffer.BlockCopy(BitConverter.GetBytes(typeName.GetHashCode()), 0, _data, 0, 4); Buffer.BlockCopy(BitConverter.GetBytes(operation.GetHashCode()), 0, _data, 4, 4); Buffer.BlockCopy(new[] { (byte)returnType }, 0, _data, 8, 1); Buffer.BlockCopy(keyValue, 0, _data, 9, keyValue.Length); } else { _data = new byte[4 + keyValue.Length]; Buffer.BlockCopy(BitConverter.GetBytes(typeName.GetHashCode()), 0, _data, 0 , 4); Buffer.BlockCopy(keyValue, 0, _data, 4 , keyValue.Length); } } }
private static HashAlgorithm GetHasher(HashAlgorithmName hashAlgorithm) { // @todo B#1208349: This is a temporary implementation that should nevertheless handle most real-world cases. To fully implement this method, // it needs to be able to handle arbitrary hash algorithms on the local CNG primitive provider's menu. There are some interop-cleanup/layering decisions // that need to made first. if (hashAlgorithm == HashAlgorithmName.MD5) return MD5.Create(); if (hashAlgorithm == HashAlgorithmName.SHA1) return SHA1.Create(); if (hashAlgorithm == HashAlgorithmName.SHA256) return SHA256.Create(); if (hashAlgorithm == HashAlgorithmName.SHA384) return SHA384.Create(); if (hashAlgorithm == HashAlgorithmName.SHA512) return SHA512.Create(); throw new NotImplementedException(SR.WorkInProgress_UnsupportedHash); // Can't handle arbitrary CNG hash algorithms yet. }
public virtual bool VerifyByPrivateKey(byte[] buffer, byte[] signature, HashAlgorithmName hashAlgorithmName) { return(VerifyByPrivateKey(buffer, signature, hashAlgorithmName, CancellationToken.None)); }
public virtual bool VerifyByPrivateKey(string text, string signature, HashAlgorithmName hashAlgorithmName, CancellationToken cancellationToken) { return(VerifyByPrivateKey(text, signature, hashAlgorithmName, Encoding.UTF8, cancellationToken)); }
public virtual bool VerifyByPrivateKey(string text, string signature, HashAlgorithmName hashAlgorithmName, Encoding encoding = null) { return(VerifyByPrivateKey(text, signature, hashAlgorithmName, encoding, CancellationToken.None)); }
/// <summary>Initializes a new instance of <see cref="SignatureAlgorithm"/>. </summary> /// <param name="id"></param> /// <param name="name"></param> /// <param name="category"></param> /// <param name="requiredKeySizeInBits"></param> /// <param name="hashAlgorithm"></param> public SignatureAlgorithm(AlgorithmId id, string name, AlgorithmCategory category, ushort requiredKeySizeInBits, HashAlgorithmName hashAlgorithm) { _id = id; _name = JsonEncodedText.Encode(name); _category = category; _requiredKeySizeInBits = requiredKeySizeInBits; _hashAlgorithm = hashAlgorithm; _sha = hashAlgorithm.Name switch { "SHA256" => Sha256.Shared, "SHA384" => Sha384.Shared, "SHA512" => Sha512.Shared, _ => ShaNull.Shared }; }
public bool VerifyByPublicKey(string text, string signature, SignatureTextTypes signatureTextType, HashAlgorithmName hashAlgorithmName, RSASignaturePadding padding, Encoding encoding = null, Func <string, byte[]> customSignatureTextConverter = null) { return(VerifyByPublicKey(text, signature, signatureTextType, hashAlgorithmName, padding, encoding, CancellationToken.None, customSignatureTextConverter)); }
public virtual bool VerifyByPublicKey(string text, string signature, HashAlgorithmName hashAlgorithmName, Encoding encoding = null) { return(VerifyByPublicKey(text, signature, hashAlgorithmName, RSASignaturePadding.Pkcs1, encoding)); }
public virtual bool VerifyByPublicKey(byte[] buffer, int offset, int count, byte[] signature, HashAlgorithmName hashAlgorithmName) { return(VerifyByPublicKey(buffer, offset, count, signature, hashAlgorithmName, CancellationToken.None)); }
private static byte[] CreatePkcs1DigestInfo(byte[] hash, HashAlgorithmName hashAlgorithm) { if (hash == null || hash.Length == 0) { throw new ArgumentNullException(nameof(hash)); } byte[] pkcs1DigestInfo = null; if (hashAlgorithm == HashAlgorithmName.MD5) { if (hash.Length != 16) { throw new ArgumentException("Invalid lenght of hash value"); } pkcs1DigestInfo = new byte[] { 0x30, 0x20, 0x30, 0x0C, 0x06, 0x08, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x02, 0x05, 0x05, 0x00, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; Array.Copy(hash, 0, pkcs1DigestInfo, pkcs1DigestInfo.Length - hash.Length, hash.Length); } else if (hashAlgorithm == HashAlgorithmName.SHA1) { if (hash.Length != 20) { throw new ArgumentException("Invalid lenght of hash value"); } pkcs1DigestInfo = new byte[] { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2B, 0x0E, 0x03, 0x02, 0x1A, 0x05, 0x00, 0x04, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; Array.Copy(hash, 0, pkcs1DigestInfo, pkcs1DigestInfo.Length - hash.Length, hash.Length); } else if (hashAlgorithm == HashAlgorithmName.SHA256) { if (hash.Length != 32) { throw new ArgumentException("Invalid lenght of hash value"); } pkcs1DigestInfo = new byte[] { 0x30, 0x31, 0x30, 0x0D, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00, 0x04, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; Array.Copy(hash, 0, pkcs1DigestInfo, pkcs1DigestInfo.Length - hash.Length, hash.Length); } else if (hashAlgorithm == HashAlgorithmName.SHA384) { if (hash.Length != 48) { throw new ArgumentException("Invalid lenght of hash value"); } pkcs1DigestInfo = new byte[] { 0x30, 0x41, 0x30, 0x0D, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05, 0x00, 0x04, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; Array.Copy(hash, 0, pkcs1DigestInfo, pkcs1DigestInfo.Length - hash.Length, hash.Length); } else if (hashAlgorithm == HashAlgorithmName.SHA512) { if (hash.Length != 64) { throw new ArgumentException("Invalid lenght of hash value"); } pkcs1DigestInfo = new byte[] { 0x30, 0x51, 0x30, 0x0D, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05, 0x00, 0x04, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; Array.Copy(hash, 0, pkcs1DigestInfo, pkcs1DigestInfo.Length - hash.Length, hash.Length); } return(pkcs1DigestInfo); }
// HasAlgorithmName was introduced into Net46 internal AsymmetricAdapter(SecurityKey key, string algorithm, HashAlgorithm hashAlgorithm, HashAlgorithmName hashAlgorithmName, bool requirePrivateKey) { HashAlgorithm = hashAlgorithm; HashAlgorithmName = hashAlgorithmName; if (key is RsaSecurityKey rsaKey) { if (rsaKey.Rsa != null) { Initialize(rsaKey.Rsa, algorithm); } else { var rsa = RSA.Create(); rsa.ImportParameters(rsaKey.Parameters); Initialize(rsa, algorithm); _disposeCryptoOperators = true; } } else if (key is X509SecurityKey x509Key) { if (requirePrivateKey) { Initialize(x509Key.Certificate.GetRSAPrivateKey(), algorithm); } else { Initialize(x509Key.Certificate.GetRSAPublicKey(), algorithm); } } else if (key is JsonWebKey rsaWebKey && rsaWebKey.Kty == JsonWebAlgorithmsKeyTypes.RSA) { var rsa = RSA.Create(); rsa.ImportParameters(rsaWebKey.CreateRsaParameters()); Initialize(rsa, algorithm); _disposeCryptoOperators = true; }
public virtual bool VerifyByPublicKey(byte[] buffer, byte[] signature, HashAlgorithmName hashAlgorithmName, RSASignaturePadding padding) { return(VerifyByPublicKey(buffer, signature, hashAlgorithmName, padding, CancellationToken.None)); }
public virtual bool VerifyByPublicKey(byte[] buffer, byte[] signature, HashAlgorithmName hashAlgorithmName) { return(VerifyByPublicKey(buffer, signature, hashAlgorithmName, RSASignaturePadding.Pkcs1)); }
public virtual bool VerifyByPublicKey(string text, string signature, HashAlgorithmName hashAlgorithmName, Encoding encoding, CancellationToken cancellationToken) { return(VerifyByPublicKey(text, signature, hashAlgorithmName, RSASignaturePadding.Pkcs1, encoding, cancellationToken)); }
public virtual bool VerifyByPublicKey(string text, string signature, HashAlgorithmName hashAlgorithmName, RSASignaturePadding padding, Encoding encoding, CancellationToken cancellationToken) { encoding = encoding.SafeEncodingValue(); return(VerifyByPublicKey(encoding.GetBytes(text), encoding.GetBytes(signature), hashAlgorithmName, padding, cancellationToken)); }
public bool VerifyByPublicKey(string text, string signature, SignatureTextTypes signatureTextType, HashAlgorithmName hashAlgorithmName, Encoding encoding = null, Func <string, byte[]> customSignatureTextConverter = null) { return(VerifyByPublicKey(text, signature, signatureTextType, hashAlgorithmName, RSASignaturePadding.Pkcs1, encoding, customSignatureTextConverter)); }
public virtual bool VerifyByPublicKey(ArraySegment <byte> buffer, byte[] signature, HashAlgorithmName hashAlgorithmName) { return(VerifyByPublicKey(buffer, signature, hashAlgorithmName, CancellationToken.None)); }
public static void ValidateDebugDirectory(Stream peStream, Stream portablePdbStreamOpt, string pdbPath, HashAlgorithmName hashAlgorithm, bool hasEmbeddedPdb, bool isDeterministic) { peStream.Position = 0; var peReader = new PEReader(peStream); var entries = peReader.ReadDebugDirectory(); int entryIndex = 0; var codeViewEntry = entries[entryIndex++]; Assert.Equal((portablePdbStreamOpt != null) ? 0x0100 : 0, codeViewEntry.MajorVersion); Assert.Equal((portablePdbStreamOpt != null) ? 0x504d : 0, codeViewEntry.MinorVersion); var codeViewData = peReader.ReadCodeViewDebugDirectoryData(codeViewEntry); Assert.Equal(1, codeViewData.Age); Assert.Equal(pdbPath, codeViewData.Path); // CodeView data: // 4B "RSDS" // 16B Guid // 4B Age // NUL-terminated path int paddedPathLength = codeViewEntry.DataSize - 24; if (isDeterministic) { Assert.Equal(Encoding.UTF8.GetByteCount(pdbPath) + 1, paddedPathLength); } else { Assert.True(paddedPathLength >= 260, "Path should be at least MAX_PATH long"); } if (portablePdbStreamOpt != null) { portablePdbStreamOpt.Position = 0; using (var provider = MetadataReaderProvider.FromPortablePdbStream(portablePdbStreamOpt, MetadataStreamOptions.LeaveOpen)) { var pdbReader = provider.GetMetadataReader(); ValidatePortablePdbId(pdbReader, codeViewEntry.Stamp, codeViewData.Guid); } } if ((portablePdbStreamOpt != null || hasEmbeddedPdb) && hashAlgorithm.Name != null) { var entry = entries[entryIndex++]; var pdbChecksumData = peReader.ReadPdbChecksumDebugDirectoryData(entry); Assert.Equal(hashAlgorithm.Name, pdbChecksumData.AlgorithmName); // TODO: validate hash } if (isDeterministic) { var entry = entries[entryIndex++]; Assert.Equal(0, entry.MinorVersion); Assert.Equal(0, entry.MajorVersion); Assert.Equal(0U, entry.Stamp); Assert.Equal(DebugDirectoryEntryType.Reproducible, entry.Type); Assert.Equal(0, entry.DataPointer); Assert.Equal(0, entry.DataRelativeVirtualAddress); Assert.Equal(0, entry.DataSize); } if (hasEmbeddedPdb) { var entry = entries[entryIndex++]; using (var provider = peReader.ReadEmbeddedPortablePdbDebugDirectoryData(entry)) { ValidatePortablePdbId(provider.GetMetadataReader(), codeViewEntry.Stamp, codeViewData.Guid); } } Assert.Equal(entries.Length, entryIndex); }
/// <summary> /// Creates an instance of <seealso cref="IRsaCrypto" /> using the provided RSAParameters objects.<para /> /// You can provide both keys or just the private key for signing, or just the public key for verification<para /> /// </summary> /// <param name="privateKey">The private key.</param> /// <param name="publicKey">The public key.</param> /// <param name="hashAlgorithmName">The hashing algorithm to use</param> /// <param name="padding">The padding to be used</param> /// <returns>An instance of <seealso cref="IRsaCrypto"/></returns> public IRsaCrypto Create(RSAParameters privateKey, RSAParameters publicKey, HashAlgorithmName hashAlgorithmName, RSASignaturePadding padding) { return(new RsaCrypto(privateKey, publicKey, hashAlgorithmName, padding)); }
public virtual bool VerifyByPublicKey(byte[] buffer, int offset, int count, byte[] signature, HashAlgorithmName hashAlgorithmName, RSASignaturePadding padding, CancellationToken cancellationToken) { if (buffer is null) { throw new ArgumentNullException(nameof(buffer)); } if (offset < 0 || offset > buffer.Length) { throw new ArgumentOutOfRangeException(nameof(offset), "Offset must be a value greater than or equal to zero and less than or equal to the length of the array."); } if (count < 0 || count > buffer.Length - offset) { throw new ArgumentOutOfRangeException(nameof(count), "Count must be a value greater than or equal to zero and less than the the remaining length of the array after the offset value."); } if (padding is null) { throw new ArgumentNullException(nameof(padding)); } return(VerifyByPublicKey(new ArraySegment <byte>(buffer, offset, count), signature, hashAlgorithmName, padding, cancellationToken)); }
/// <summary> /// Creates an instance of <seealso cref="IRsaCrypto"/> using the provided keys.<para /> /// You can provide both keys or just the private key for signing, or just the public key for verification<para /> /// The keys can be extracted in xml format from the <seealso cref="IRsaCrypto.PublicKey"/> and <seealso cref="IRsaCrypto.PrivateKey"/> properties<para /> /// </summary> /// <param name="privateKeyXml">The private key xml.</param> /// <param name="publicKeyXml">The public key xml.</param> /// <param name="hashAlgorithmName">The hashing algorithm to use</param> /// <param name="padding">The padding to be used</param> /// <returns>An instance of <seealso cref="IRsaCrypto"/></returns> public IRsaCrypto Create(string privateKeyXml, string publicKeyXml, HashAlgorithmName hashAlgorithmName, RSASignaturePadding padding) { return(new RsaCrypto(privateKeyXml, publicKeyXml, hashAlgorithmName, padding)); }
public bool VerifyByPrivateKey(string text, string signature, SignatureTextTypes signatureTextType, HashAlgorithmName hashAlgorithmName, CancellationToken cancellationToken, Func <string, byte[]> customSignatureTextConverter = null) { return(VerifyByPrivateKey(text, signature, signatureTextType, hashAlgorithmName, Encoding.UTF8, cancellationToken, customSignatureTextConverter)); }
/// <summary> /// Creates an instance of <seealso cref="IRsaCrypto" /> using the provided key size, hashing and padding values<para /> /// </summary> /// <param name="keySize">The integer key size to use</param> /// <param name="hashAlgorithmName">The hashing algorithm to use</param> /// <param name="padding">The padding to be used</param> /// <returns>An instance of <seealso cref="IRsaCrypto"/></returns> public IRsaCrypto Create(int keySize, HashAlgorithmName hashAlgorithmName, RSASignaturePadding padding) { var c = new RsaCrypto(keySize, hashAlgorithmName, padding); return(c); }
public virtual bool VerifyByPublicKey(string text, string signature, HashAlgorithmName hashAlgorithmName, RSASignaturePadding padding, Encoding encoding = null) { return(VerifyByPublicKey(text, signature, hashAlgorithmName, padding, encoding, CancellationToken.None)); }
protected abstract bool VerifyByPrivateKeyInternal(ArraySegment <byte> buffer, byte[] signature, HashAlgorithmName hashAlgorithmName, CancellationToken cancellationToken);
public ECDsaSignatureAlgorithm(HashAlgorithmName hashAlgorithm, ECDsa ecdsa) { HashAlgorithm = hashAlgorithm; _ecdsa = ecdsa ?? throw new ArgumentNullException(nameof(ecdsa)); }
internal SignerInfoAsn Sign( ReadOnlyMemory <byte> data, string?contentTypeOid, bool silent, out X509Certificate2Collection chainCerts) { HashAlgorithmName hashAlgorithmName = PkcsHelpers.GetDigestAlgorithm(SigningPolicy.DigestAlgorithmOID); IncrementalHash hasher = IncrementalHash.CreateHash(hashAlgorithmName); hasher.AppendData(data.Span); byte[] dataHash = hasher.GetHashAndReset(); SignerInfoAsn newSignerInfo = default; newSignerInfo.DigestAlgorithm.Algorithm = new Oid(SigningPolicy.DigestAlgorithmOID); newSignerInfo.DigestAlgorithm.Parameters = SigningPolicy.DigestAlgorithmParameters; // If the user specified attributes (not null, count > 0) we need attributes. // If the content type is null we're counter-signing, and need the message digest attr. // If the content type is otherwise not-data we need to record it as the content-type attr. if (SignedAttributes?.Count > 0 || contentTypeOid != Oids.Pkcs7Data) { List <AttributeAsn> signedAttrs = BuildAttributes(SignedAttributes); using (var writer = new AsnWriter(AsnEncodingRules.DER)) { writer.WriteOctetString(dataHash); signedAttrs.Add( new AttributeAsn { AttrType = new Oid(Oids.MessageDigest, Oids.MessageDigest), AttrValues = new[] { new ReadOnlyMemory <byte>(writer.Encode()) }, }); } if (contentTypeOid != null) { using (var writer = new AsnWriter(AsnEncodingRules.DER)) { writer.WriteObjectIdentifier(contentTypeOid); signedAttrs.Add( new AttributeAsn { AttrType = new Oid(Oids.ContentType, Oids.ContentType), AttrValues = new[] { new ReadOnlyMemory <byte>(writer.Encode()) }, }); } } // Use the serializer/deserializer to DER-normalize the attribute order. SignedAttributesSet signedAttrsSet = default; signedAttrsSet.SignedAttributes = PkcsHelpers.NormalizeAttributeSet( signedAttrs.ToArray(), normalized => hasher.AppendData(normalized)); // Since this contains user data in a context where BER is permitted, use BER. // There shouldn't be any observable difference here between BER and DER, though, // since the top level fields were written by NormalizeSet. using (AsnWriter attrsWriter = new AsnWriter(AsnEncodingRules.BER)) { signedAttrsSet.Encode(attrsWriter); newSignerInfo.SignedAttributes = attrsWriter.Encode(); } dataHash = hasher.GetHashAndReset(); } switch (SignerIdentifierType) { case SubjectIdentifierType.IssuerAndSerialNumber: byte[] serial = Certificate !.GetSerialNumber(); Array.Reverse(serial); newSignerInfo.Sid.IssuerAndSerialNumber = new IssuerAndSerialNumberAsn { Issuer = Certificate.IssuerName.RawData, SerialNumber = serial, }; newSignerInfo.Version = 1; break; case SubjectIdentifierType.SubjectKeyIdentifier: // newSignerInfo.Sid.SubjectKeyIdentifier = PkcsPal.Instance.GetSubjectKeyIdentifier(Certificate!); newSignerInfo.Version = 3; break; case SubjectIdentifierType.NoSignature: newSignerInfo.Sid.IssuerAndSerialNumber = new IssuerAndSerialNumberAsn { Issuer = SubjectIdentifier.DummySignerEncodedValue, SerialNumber = new byte[1], }; newSignerInfo.Version = 1; break; default: Debug.Fail($"Unresolved SignerIdentifierType value: {SignerIdentifierType}"); throw new CryptographicException(); } if (UnsignedAttributes != null && UnsignedAttributes.Count > 0) { List <AttributeAsn> attrs = BuildAttributes(UnsignedAttributes); newSignerInfo.UnsignedAttributes = PkcsHelpers.NormalizeAttributeSet(attrs.ToArray()); } bool signed; Oid? signatureAlgorithm; ReadOnlyMemory <byte> signatureValue; if (SignerIdentifierType == SubjectIdentifierType.NoSignature) { signatureAlgorithm = new Oid(Oids.NoSignature, null); signatureValue = dataHash; signed = true; } else { signed = _signer.Sign(dataHash, hashAlgorithmName, Certificate !, PrivateKey, silent, out signatureAlgorithm, out signatureValue); } if (!signed) { throw new CryptographicException(Strings.Cryptography_Cms_CannotDetermineSignatureAlgorithm); } newSignerInfo.SignatureValue = signatureValue; newSignerInfo.SignatureAlgorithm.Algorithm = new Oid(SigningPolicy.EncryptionAlgorithmOID, SigningPolicy.SignatureAlgorithmName); newSignerInfo.SignatureAlgorithm.Parameters = SigningPolicy.SigningParameters; X509Certificate2Collection certs = new X509Certificate2Collection(); certs.AddRange(Certificates); if (SignerIdentifierType != SubjectIdentifierType.NoSignature) { if (IncludeOption == X509IncludeOption.EndCertOnly) { certs.Add(Certificate !); } else if (IncludeOption != X509IncludeOption.None) { X509Chain chain = new X509Chain(); chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllFlags; if (!chain.Build(Certificate !)) { foreach (X509ChainStatus status in chain.ChainStatus) { if (status.Status == X509ChainStatusFlags.PartialChain) { throw new CryptographicException(Strings.Cryptography_Cms_IncompleteCertChain); } } } X509ChainElementCollection elements = chain.ChainElements; int count = elements.Count; int last = count - 1; if (last == 0) { // If there's always one cert treat it as EE, not root. last = -1; } for (int i = 0; i < count; i++) { X509Certificate2 cert = elements[i].Certificate; if (i == last && IncludeOption == X509IncludeOption.ExcludeRoot && cert.SubjectName.RawData.AsSpan().SequenceEqual(cert.IssuerName.RawData)) { break; } certs.Add(cert); } } } chainCerts = certs; return(newSignerInfo); }
public virtual bool VerifyByPrivateKey(ArraySegment <byte> buffer, byte[] signature, HashAlgorithmName hashAlgorithmName, CancellationToken cancellationToken) { return(VerifyByPrivateKeyInternal(buffer, signature, hashAlgorithmName, cancellationToken)); }
public static void ChainCertRequirements(bool useIntermed, bool?isCA, X509KeyUsageFlags keyUsage, bool expectSuccess) { HashAlgorithmName hashAlgorithm = HashAlgorithmName.SHA384; ECDsa rootKey = null; ECDsa intermedKey = null; ECDsa leafKey = null; X509Certificate2 rootCert = null; X509Certificate2 intermedCert = null; X509Certificate2 leafCert = null; try { rootKey = ECDsa.Create(ECCurve.NamedCurves.nistP384); var request = new CertificateRequest("CN=Root", rootKey, hashAlgorithm); if (useIntermed || isCA.HasValue) { request.CertificateExtensions.Add( new X509BasicConstraintsExtension(useIntermed || isCA.Value, false, 0, true)); } X509KeyUsageFlags rootFlags = useIntermed ? X509KeyUsageFlags.KeyCertSign : keyUsage; if (rootFlags != X509KeyUsageFlags.None) { request.CertificateExtensions.Add(new X509KeyUsageExtension(rootFlags, true)); } DateTimeOffset start = DateTimeOffset.UtcNow.AddHours(-1); DateTimeOffset end = start.AddHours(2); rootCert = request.CreateSelfSigned(start, end); X509Certificate2 signerCert = rootCert; if (useIntermed) { intermedKey = ECDsa.Create(ECCurve.NamedCurves.nistP384); request = new CertificateRequest("CN=Intermediate", intermedKey, hashAlgorithm); if (isCA.HasValue) { request.CertificateExtensions.Add( new X509BasicConstraintsExtension(isCA.Value, false, 0, true)); } if (keyUsage != X509KeyUsageFlags.None) { request.CertificateExtensions.Add(new X509KeyUsageExtension(keyUsage, true)); } using (X509Certificate2 tmp = request.Create(rootCert, start, end, new byte[] { 6, 0, 2, 2, 10, 23 })) { intermedCert = tmp.CopyWithPrivateKey(intermedKey); } signerCert = intermedCert; } leafKey = ECDsa.Create(ECCurve.NamedCurves.nistP256); request = new CertificateRequest("CN=Leaf", leafKey, hashAlgorithm); byte[] leafSerialNumber = { 2, 4, 6, 0, 1 }; if (!expectSuccess) { AssertExtensions.Throws <ArgumentException>( "issuerCertificate", () => { request.Create(signerCert, start, end, leafSerialNumber)?.Dispose(); }); return; } leafCert = request.Create(signerCert, start, end, leafSerialNumber); using (X509Chain chain = new X509Chain()) { chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; chain.ChainPolicy.ExtraStore.Add(rootCert); chain.ChainPolicy.VerificationTime = start.UtcDateTime; chain.AllowUnknownAuthorityOrAddSelfSignedToCustomTrust(rootCert); if (useIntermed) { chain.ChainPolicy.ExtraStore.Add(intermedCert); } RunChain(chain, leafCert, true, "Chain verification"); DisposeChainCerts(chain); } } finally { leafCert?.Dispose(); leafKey?.Dispose(); intermedCert?.Dispose(); intermedKey?.Dispose(); rootCert?.Dispose(); rootKey?.Dispose(); } }
public bool VerifyByPrivateKey(string text, string signature, SignatureTextTypes signatureTextType, HashAlgorithmName hashAlgorithmName, Encoding encoding, CancellationToken cancellationToken, Func <string, byte[]> customSignatureTextConverter = null) { encoding = encoding.SafeEncodingValue(); var finalSignature = signatureTextType.GetBytes(signature, encoding, customSignatureTextConverter); return(VerifyByPrivateKey(encoding.GetBytes(text), finalSignature, hashAlgorithmName, CancellationToken.None)); }
public abstract byte[] SignData(byte[] data, HashAlgorithmName hashAlgorithm);
public virtual bool VerifyByPublicKey(byte[] buffer, int offset, int count, byte[] signature, HashAlgorithmName hashAlgorithmName, CancellationToken cancellationToken) { return(VerifyByPublicKey(buffer, offset, count, signature, hashAlgorithmName, RSASignaturePadding.Pkcs1, cancellationToken)); }