Exemple #1
0
        public bool VerifyData(byte[] data, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
        {
            if (data == null)
                throw new ArgumentNullException(nameof(data));

            return VerifyData(data, 0, data.Length, signature, hashAlgorithm, padding);
        }
Exemple #2
0
        /// <summary>
        ///     Computes the signature of a hash that was produced by the hash algorithm specified by "hashAlgorithm."
        /// </summary>
        public override byte[] SignHash(byte[] hash, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
        {
            if (hash == null)
                throw new ArgumentNullException("hash");

            unsafe
            {
                byte[] signature = null;
                SignOrVerify(padding, hashAlgorithm, hash,
                    delegate (AsymmetricPaddingMode paddingMode, void* pPaddingInfo)
                    {
                        SafeNCryptKeyHandle keyHandle = Key.Handle;
                        int numBytesNeeded;
                        ErrorCode errorCode = Interop.NCrypt.NCryptSignHash(keyHandle, pPaddingInfo, hash, hash.Length, null, 0, out numBytesNeeded, paddingMode);
                        if (errorCode != ErrorCode.ERROR_SUCCESS)
                            throw errorCode.ToCryptographicException();

                        signature = new byte[numBytesNeeded];
                        errorCode = Interop.NCrypt.NCryptSignHash(keyHandle, pPaddingInfo, hash, hash.Length, signature, signature.Length, out numBytesNeeded, paddingMode);
                        if (errorCode != ErrorCode.ERROR_SUCCESS)
                            throw errorCode.ToCryptographicException();
                    }
                );
                return signature;
            }
        }
Exemple #3
0
        /// <summary>
        ///     Verifies that alleged signature of a hash is, in fact, a valid signature of that hash.
        /// </summary>
        public override bool VerifyHash(byte[] hash, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
        {
            if (hash == null)
                throw new ArgumentNullException("hash");
            if (signature == null)
                throw new ArgumentNullException("signature");

            unsafe
            {
                bool verified = false;
                SignOrVerify(padding, hashAlgorithm, hash,
                    delegate (AsymmetricPaddingMode paddingMode, void* pPaddingInfo)
                    {
                        SafeNCryptKeyHandle keyHandle = Key.Handle;
                        ErrorCode errorCode = Interop.NCrypt.NCryptVerifySignature(keyHandle, pPaddingInfo, hash, hash.Length, signature, signature.Length, paddingMode);
                        if (errorCode == ErrorCode.ERROR_SUCCESS)
                            verified = true;
                        else if (errorCode == ErrorCode.NTE_BAD_SIGNATURE)
                            verified = false;
                        else
                            throw errorCode.ToCryptographicException();
                    }
                );
                return verified;
            }
        }
        /// <summary>
        ///     Computes the signature of a hash that was produced by the hash algorithm specified by "hashAlgorithm."
        /// </summary>
        public override byte[] SignHash(byte[] hash, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
        {
            if (hash == null)
                throw new ArgumentNullException("hash");

            unsafe
            {
                byte[] signature = null;
                SignOrVerify(padding, hashAlgorithm, hash,
                    delegate (AsymmetricPaddingMode paddingMode, void* pPaddingInfo)
                    {
                        int estimatedSize = KeySize / 8;
#if DEBUG
                        estimatedSize = 2;  // Make sure the NTE_BUFFER_TOO_SMALL scenario gets exercised.
#endif
                        SafeNCryptKeyHandle keyHandle = Key.Handle;

                        signature = new byte[estimatedSize];
                        int numBytesNeeded;
                        ErrorCode errorCode = Interop.NCrypt.NCryptSignHash(keyHandle, pPaddingInfo, hash, hash.Length, signature, signature.Length, out numBytesNeeded, paddingMode);
                        if (errorCode == ErrorCode.NTE_BUFFER_TOO_SMALL)
                        {
                            signature = new byte[numBytesNeeded];
                            errorCode = Interop.NCrypt.NCryptSignHash(keyHandle, pPaddingInfo, hash, hash.Length, signature, signature.Length, out numBytesNeeded, paddingMode);
                        }
                        if (errorCode != ErrorCode.ERROR_SUCCESS)
                            throw errorCode.ToCryptographicException();

                        Array.Resize(ref signature, numBytesNeeded);
                    }
                );
                return signature;
            }
        }
Exemple #5
0
        public byte[] SignData(byte[] data, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
        {
            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }

            return SignData(data, 0, data.Length, hashAlgorithm, padding);
        }
Exemple #6
0
        public virtual byte[] SignData(Stream data, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
        {
            if (data == null)
                throw new ArgumentNullException(nameof(data));
            if (string.IsNullOrEmpty(hashAlgorithm.Name))
                throw HashAlgorithmNameNullOrEmpty();
            if (padding == null)
                throw new ArgumentNullException(nameof(padding));

            byte[] hash = HashData(data, hashAlgorithm);
            return SignHash(hash, hashAlgorithm, padding);
        }
Exemple #7
0
        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);
            }
        }
 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();
 }
Exemple #9
0
        /// <summary>
        ///     Computes the signature of a hash that was produced by the hash algorithm specified by "hashAlgorithm."
        /// </summary>
        public override byte[] SignHash(byte[] hash, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
        {
            if (hash == null)
                throw new ArgumentNullException(nameof(hash));

            unsafe
            {
                byte[] signature = null;
                SignOrVerify(padding, hashAlgorithm, hash,
                    delegate (AsymmetricPaddingMode paddingMode, void* pPaddingInfo)
                    {
                        int estimatedSize = KeySize / 8;
                        signature = GetKeyHandle().SignHash(hash, paddingMode, pPaddingInfo, estimatedSize);
                    }
                );
                return signature;
            }
        }
Exemple #10
0
        /// <summary>
        ///     Verifies that alleged signature of a hash is, in fact, a valid signature of that hash.
        /// </summary>
        public override bool VerifyHash(byte[] hash, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
        {
            if (hash == null)
                throw new ArgumentNullException(nameof(hash));
            if (signature == null)
                throw new ArgumentNullException(nameof(signature));

            unsafe
            {
                bool verified = false;
                SignOrVerify(padding, hashAlgorithm, hash,
                    delegate (AsymmetricPaddingMode paddingMode, void* pPaddingInfo)
                    {
                        verified = GetKeyHandle().VerifyHash(hash, signature, paddingMode, pPaddingInfo);
                    }
                );
                return verified;
            }
        }
Exemple #11
0
        //
        // Common helper for SignHash() and VerifyHash(). Creates the necessary PADDING_INFO structure based on the chosen padding mode and then passes it
        // to "signOrVerify" which performs the actual signing or verification.
        //
        private static unsafe void SignOrVerify(RSASignaturePadding padding, HashAlgorithmName hashAlgorithm, byte[] hash, SignOrVerifyAction signOrVerify)
        {
            string hashAlgorithmName = hashAlgorithm.Name;
            if (string.IsNullOrEmpty(hashAlgorithmName))
                throw new ArgumentException(SR.Cryptography_HashAlgorithmNameNullOrEmpty, "hashAlgorithm");

            if (padding == null)
                throw new ArgumentNullException("padding");

            switch (padding.Mode)
            {
                case RSASignaturePaddingMode.Pkcs1:
                    {
                        using (SafeUnicodeStringHandle safeHashAlgorithmName = new SafeUnicodeStringHandle(hashAlgorithmName))
                        {
                            BCRYPT_PKCS1_PADDING_INFO paddingInfo = new BCRYPT_PKCS1_PADDING_INFO()
                            {
                                pszAlgId = safeHashAlgorithmName.DangerousGetHandle(),
                            };
                            signOrVerify(AsymmetricPaddingMode.NCRYPT_PAD_PKCS1_FLAG, &paddingInfo);
                        }
                        break;
                    }

                case RSASignaturePaddingMode.Pss:
                    {
                        using (SafeUnicodeStringHandle safeHashAlgorithmName = new SafeUnicodeStringHandle(hashAlgorithmName))
                        {
                            BCRYPT_PSS_PADDING_INFO paddingInfo = new BCRYPT_PSS_PADDING_INFO()
                            {
                                pszAlgId = safeHashAlgorithmName.DangerousGetHandle(),
                                cbSalt = hash.Length,
                            };
                            signOrVerify(AsymmetricPaddingMode.NCRYPT_PAD_PSS_FLAG, &paddingInfo);
                        }
                        break;
                    }

                default:
                    throw new CryptographicException(SR.Cryptography_UnsupportedPaddingMode);
            }
        }
Exemple #12
0
        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);
        }
        /// <summary>
        ///     Verifies that alleged signature of a hash is, in fact, a valid signature of that hash.
        /// </summary>
        public override bool VerifyHash(byte[] hash, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
        {
            if (hash == null)
                throw new ArgumentNullException("hash");
            if (signature == null)
                throw new ArgumentNullException("signature");

            unsafe
            {
                bool verified = false;
                SignOrVerify(padding, hashAlgorithm, hash,
                    delegate (AsymmetricPaddingMode paddingMode, void* pPaddingInfo)
                    {
                        SafeNCryptKeyHandle keyHandle = Key.Handle;
                        ErrorCode errorCode = Interop.NCrypt.NCryptVerifySignature(keyHandle, pPaddingInfo, hash, hash.Length, signature, signature.Length, paddingMode);
                        verified = (errorCode == ErrorCode.ERROR_SUCCESS);  // For consistency with other RSA classes, return "false" for any error code rather than making the caller catch an exception.
                    }
                );
                return verified;
            }
        }
Exemple #14
0
        public virtual bool VerifyData(
            byte[] data,
            int offset,
            int count,
            byte[] signature,
            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 (signature == null)
                throw new ArgumentNullException("signature");
            if (string.IsNullOrEmpty(hashAlgorithm.Name))
                throw HashAlgorithmNameNullOrEmpty();
            if (padding == null)
                throw new ArgumentNullException("padding");

            byte[] hash = HashData(data, offset, count, hashAlgorithm);
            return VerifyHash(hash, signature, hashAlgorithm, padding);
        }
Exemple #15
0
        protected override ISignValue SignByPublicKeyInternal(ArraySegment <byte> buffer, HashAlgorithmName hashAlgorithmName, RSASignaturePadding padding, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            if (!Key.IncludePublicKey())
            {
                throw new ArgumentException("There is no PublicKey in current RsaKey instance.");
            }
            var rsa = TouchRsaUtilFromPublicKey(Key.Format, Encoding.UTF8, Key.PublicKey, Key.Size);

            var signature = rsa.SignByPublicKey(buffer.ToArray(), hashAlgorithmName, padding);

            return(CreateSignValue(signature));
        }
 public virtual ISignValue SignByPrivateKey(string text, HashAlgorithmName hashAlgorithmName, RSASignaturePadding padding, Encoding encoding, CancellationToken cancellationToken)
 {
     return(SignByPrivateKey(encoding.SafeEncodingValue().GetBytes(text), hashAlgorithmName, padding, cancellationToken));
 }
Exemple #17
0
        /// <summary>
        /// Create a CertificateRequest for the specified subject name, RSA key, and hash algorithm.
        /// </summary>
        /// <param name="subjectName">
        ///   The string representation of the subject name for the certificate or certificate request.
        /// </param>
        /// <param name="key">
        ///   An RSA key whose public key material will be included in the certificate or certificate request.
        ///   This key will be used as a private key if <see cref="CreateSelfSigned" /> is called.
        /// </param>
        /// <param name="hashAlgorithm">
        ///   The hash algorithm to use when signing the certificate or certificate request.
        /// </param>
        /// <param name="padding">
        ///   The RSA signature padding to apply if self-signing or being signed with an <see cref="X509Certificate2" />.
        /// </param>
        /// <seealso cref="X500DistinguishedName(string)"/>
        public CertificateRequest(string subjectName, RSA key, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
        {
            ArgumentNullException.ThrowIfNull(subjectName);
            ArgumentNullException.ThrowIfNull(key);
            ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm));
            ArgumentNullException.ThrowIfNull(padding);

            SubjectName = new X500DistinguishedName(subjectName);

            _key          = key;
            _generator    = X509SignatureGenerator.CreateForRSA(key, padding);
            _rsaPadding   = padding;
            PublicKey     = _generator.PublicKey;
            HashAlgorithm = hashAlgorithm;
        }
Exemple #18
0
        /// <summary>
        /// Verifies that the base64 encoded signature is valid by comparing the hashed data with the decrypted signature.
        /// </summary>
        /// <param name="hashedData">Hashed data to be verified</param>
        /// <param name="signedData">The signed data</param>
        /// <param name="publicKey">Public key that is the RSA pair of the private key that signed the message</param>
        /// <param name="hashAlgorithm">The algorithm used for signing</param>
        /// <param name="padding">The padding that was used in the signature</param>
        /// <returns>Return true if data is Verified</returns>
        /// <exception cref="ArgumentException">There is null in the parameters or one of the parameters empty</exception>
        /// <exception cref="CryptographicException">The cryptographic service provider (CSP) cannot be acquired.-or- The parameters parameter has missing fields.</exception>
        public static bool VerifyHash(byte[] hashedData, byte[] signedData, X509Certificate2 publicKey, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
        {
            try
            {
                RSAParameters Params = publicKey.GetRSAPublicKey().ExportParameters(false);

                using (var rsa = new RSACryptoServiceProvider())
                {
                    rsa.ImportParameters(Params);
                    return(rsa.VerifyHash(hashedData, signedData, hashAlgorithm, padding));
                }
            }
            catch (ArgumentException ex)
            {
                throw ex;
            }
            catch (CryptographicException ex)
            {
                throw ex;
            }
        }
Exemple #19
0
 public RsaDigitalSignatureService(int keySize, HashAlgorithmName name, RSASignaturePadding padding)
 {
     this.keySize = keySize;
     this.name    = name;
     this.padding = padding;
 }
Exemple #20
0
 protected abstract byte[] SignHash(RSA rsa, byte[] hash, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding);
Exemple #21
0
 /// <summary>
 /// Computes the signature for the specified hash value by encrypting it with the private key.
 /// </summary>
 /// <param name="hash">Hashed data to be signed</param>
 /// <param name="privateKey">The private key used for signing</param>
 /// <param name="hashAlgorithm">The algorithm that will be used for signing</param>
 /// <param name="padding">The padding that will be used in the signature</param>
 /// <returns>Return signed hash as byte array, or null if fails</returns>
 /// <exception cref="ArgumentException">There is null in the parameters or one of the parameters empty</exception>
 /// <exception cref="CryptographicException">The cryptographic service provider (CSP) cannot be acquired.-or- The parameters parameter has missing fields. -or- The padding mode is not supported. -or- The certificate context is invalid.</exception>
 public static byte[] SignHash(byte[] hash, X509Certificate2 privateKey, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
 {
     try
     {
         RSAParameters Params = privateKey.GetRSAPrivateKey().ExportParameters(true);
         if (privateKey.HasPrivateKey)
         {
             using (var rsa = new RSACryptoServiceProvider())
             {
                 rsa.ImportParameters(Params);
                 byte[] signedBytes = rsa.SignHash(hash, hashAlgorithm, padding);
                 return(signedBytes);
             }
         }
     }
     catch (ArgumentException ex)
     {
         throw ex;
     }
     catch (CryptographicException ex)
     {
         throw ex;
     }
     return(null);
 }
Exemple #22
0
        /// <summary>
        /// 数据签名
        /// </summary>
        /// <param name="data">待签名数据</param>
        /// <param name="privateKey">私钥</param>
        /// <param name="signaturePadding">签名类型</param>
        /// <param name="hashAlgorithmName">哈希算法</param>
        /// <param name="encode">编码</param>
        /// <returns></returns>
        public static string SignDataAsBase64(string data, string privateKey, RSASignaturePadding signaturePadding = null, string hashAlgorithmName = "SHA256", string encode = "utf-8")
        {
            var signedData = SignData(Encoding.GetEncoding(encode).GetBytes(data), privateKey, signaturePadding, hashAlgorithmName);

            return(Convert.ToBase64String(signedData));
        }
Exemple #23
0
        public static void CreateChain_RSAPSS()
        {
            using (RSA rootKey = RSA.Create())
                using (RSA intermedKey = RSA.Create())
                    using (RSA leafKey = RSA.Create(TestData.RsaBigExponentParams))
                    {
                        X509Certificate2   rootCertWithKey     = null;
                        X509Certificate2   intermedCertWithKey = null;
                        X509Certificate2   leafCert            = null;
                        CertificateRequest request;

                        RSASignaturePadding padding = RSASignaturePadding.Pss;

                        DateTimeOffset notBefore = DateTimeOffset.UtcNow;
                        DateTimeOffset notAfter  = notBefore.AddHours(1);

                        try
                        {
                            request = new CertificateRequest("CN=Root", rootKey, HashAlgorithmName.SHA512, padding);
                            request.CertificateExtensions.Add(
                                new X509BasicConstraintsExtension(true, false, 0, true));

                            rootCertWithKey = request.CreateSelfSigned(notBefore, notAfter);

                            byte[] intermedSerial = { 1, 2, 3, 5, 7, 11, 13 };

                            request = new CertificateRequest("CN=Intermediate", intermedKey, HashAlgorithmName.SHA384, padding);
                            request.CertificateExtensions.Add(
                                new X509BasicConstraintsExtension(true, true, 1, true));

                            X509Certificate2 intermedPublic = request.Create(rootCertWithKey, notBefore, notAfter, intermedSerial);
                            intermedCertWithKey = intermedPublic.CopyWithPrivateKey(intermedKey);
                            intermedPublic.Dispose();

                            request = new CertificateRequest("CN=Leaf", leafKey, HashAlgorithmName.SHA256, padding);
                            request.CertificateExtensions.Add(
                                new X509BasicConstraintsExtension(false, false, 0, true));

                            byte[] leafSerial = { 1, 1, 2, 6, 12, 60, 60, };

                            leafCert = request.Create(intermedCertWithKey, notBefore, notAfter, leafSerial);

                            using (X509Chain chain = new X509Chain())
                            {
                                chain.ChainPolicy.RevocationMode    = X509RevocationMode.NoCheck;
                                chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority;
                                chain.ChainPolicy.ExtraStore.Add(intermedCertWithKey);
                                chain.ChainPolicy.ExtraStore.Add(rootCertWithKey);
                                chain.ChainPolicy.VerificationTime = notBefore.ToLocalTime().DateTime;

                                RunChain(chain, leafCert, true, "Chain build");
                                DisposeChainCerts(chain);
                            }
                        }
                        finally
                        {
                            leafCert?.Dispose();
                            intermedCertWithKey?.Dispose();
                            rootCertWithKey?.Dispose();
                        }
                    }
        }
 protected override byte[] SignData(RSA rsa, byte[] data, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) =>
 TryWithOutputArray(dest => rsa.TrySignData(data, dest, hashAlgorithm, padding, out int bytesWritten) ? (true, bytesWritten) : (false, 0));
Exemple #25
0
 public override bool VerifyHash(byte[] hash, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) =>
 VerifyHashDelegate(hash, signature, hashAlgorithm, padding);
Exemple #26
0
 public override byte[] SignHash(byte[] hash, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) =>
 SignHashDelegate(hash, hashAlgorithm, padding);
Exemple #27
0
        /// <summary>
        /// Create a CertificateRequest for the specified subject name, RSA key, and hash algorithm.
        /// </summary>
        /// <param name="subjectName">
        ///   The string representation of the subject name for the certificate or certificate request.
        /// </param>
        /// <param name="key">
        ///   An RSA key whose public key material will be included in the certificate or certificate request.
        ///   This key will be used as a private key if <see cref="CreateSelfSigned" /> is called.
        /// </param>
        /// <param name="hashAlgorithm">
        ///   The hash algorithm to use when signing the certificate or certificate request.
        /// </param>
        /// <param name="padding">
        ///   The RSA signature padding to apply if self-signing or being signed with an <see cref="X509Certificate2" />.
        /// </param>
        /// <seealso cref="X500DistinguishedName(string)"/>
        public CertificateRequest(string subjectName, RSA key, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
        {
            if (subjectName == null)
            {
                throw new ArgumentNullException(nameof(subjectName));
            }
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }
            if (string.IsNullOrEmpty(hashAlgorithm.Name))
            {
                throw new ArgumentException(SR.Cryptography_HashAlgorithmNameNullOrEmpty, nameof(hashAlgorithm));
            }
            if (padding == null)
            {
                throw new ArgumentNullException(nameof(padding));
            }

            SubjectName = new X500DistinguishedName(subjectName);

            _key          = key;
            _generator    = X509SignatureGenerator.CreateForRSA(key, padding);
            _rsaPadding   = padding;
            PublicKey     = _generator.PublicKey;
            HashAlgorithm = hashAlgorithm;
        }
Exemple #28
0
 /// <summary>
 /// 签名校验
 /// </summary>
 /// <param name="data">原数据</param>
 /// <param name="signature">签名后数据</param>
 /// <param name="publicKey">公寓奥</param>
 /// <param name="signaturePadding">签名算法</param>
 /// <param name="hashAlgorithmName">哈希算法</param>
 /// <returns></returns>
 public static bool VerifyData(byte[] data, byte[] signature, string publicKey, RSASignaturePadding signaturePadding = null, string hashAlgorithmName = "SHA256")
 {
     using var rsa = CreateRsaFromPublicKey(publicKey);
     signaturePadding ??= RSASignaturePadding.Pkcs1;
     return(rsa.VerifyData(data, signature, HashAlgorithmNameDict[hashAlgorithmName], signaturePadding));
 }
Exemple #29
0
        public override bool VerifyHash(byte[] hash, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
        {
            if (hash == null)
            {
                throw new ArgumentNullException("hash");
            }
            if (signature == null)
            {
                throw new ArgumentNullException("signature");
            }
            if (String.IsNullOrEmpty(hashAlgorithm.Name))
            {
                throw new ArgumentException(SR.GetString(SR.Cryptography_HashAlgorithmNameNullOrEmpty), "hashAlgorithm");
            }
            if (padding == null)
            {
                throw new ArgumentNullException("padding");
            }

            if (padding == RSASignaturePadding.Pkcs1)
            {
                return NCryptNative.VerifySignaturePkcs1(KeyHandle, hash, hashAlgorithm.Name, signature);
            }
            else if (padding == RSASignaturePadding.Pss)
            {
                return NCryptNative.VerifySignaturePss(KeyHandle, hash, hashAlgorithm.Name, hash.Length, signature);
            }
            else
            {
                 // no other padding possibilities at present, but we might version independently from more being added.
                 throw new CryptographicException(SR.GetString(SR.Cryptography_UnsupportedPaddingMode));
            }
        }
Exemple #30
0
        /// <summary>
        /// 签名校验
        /// </summary>
        /// <param name="data">源数据</param>
        /// <param name="base64Signature">签名后数据Base64编码</param>
        /// <param name="publicKey">公寓奥</param>
        /// <param name="signaturePadding">签名算法</param>
        /// <param name="hashAlgorithmName">哈希算法</param>
        /// <param name="encode">编码</param>
        /// <returns></returns>
        public static bool VerifyBase64Data(string data, string base64Signature, string publicKey, RSASignaturePadding signaturePadding = null, string hashAlgorithmName = "SHA256", string encode = "utf-8")
        {
            var dataBytes = Encoding.GetEncoding(encode).GetBytes(data);
            var signature = Convert.FromBase64String(base64Signature);

            return(VerifyData(dataBytes, signature, publicKey, signaturePadding, hashAlgorithmName));
        }
Exemple #31
0
 protected abstract byte[] SignData(RSA rsa, byte[] data, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding);
Exemple #32
0
        public bool VerifyData(Stream data, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
        {
            if (data == null)
                throw new ArgumentNullException(nameof(data));
            if (signature == null)
                throw new ArgumentNullException(nameof(signature));
            if (string.IsNullOrEmpty(hashAlgorithm.Name))
                throw HashAlgorithmNameNullOrEmpty();
            if (padding == null)
                throw new ArgumentNullException(nameof(padding));

            byte[] hash = HashData(data, hashAlgorithm);
            return VerifyHash(hash, signature, hashAlgorithm, padding);
        }
Exemple #33
0
 protected abstract bool VerifyHash(RSA rsa, byte[] hash, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding);
Exemple #34
0
 public abstract bool VerifyHash(byte[] hash, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding);
Exemple #35
0
		public override bool VerifyHash (byte[] hash, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
		{
			throw new NotImplementedException ();
		}
 public virtual ISignValue SignByPrivateKey(ArraySegment <byte> buffer, HashAlgorithmName hashAlgorithmName, RSASignaturePadding padding, CancellationToken cancellationToken)
 {
     return(SignByPrivateKeyInternal(buffer, hashAlgorithmName, padding, cancellationToken));
 }
Exemple #37
0
        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);
            }
        }
Exemple #38
0
        protected override bool VerifyByPrivateKeyInternal(ArraySegment <byte> buffer, byte[] signature, HashAlgorithmName hashAlgorithmName, RSASignaturePadding padding, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            if (!Key.IncludePrivateKey())
            {
                throw new ArgumentException("There is no PrivateKey in current RsaKey instance.");
            }
            var rsa = TouchRsaUtilFromPublicKey(Key.Format, Encoding.UTF8, Key.PrivateKey, Key.Size);

            return(rsa.VerifyByPrivateKey(buffer.ToArray(), signature, hashAlgorithmName, padding));
        }
Exemple #39
0
 public abstract byte[] SignHash(byte[] hash, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding);
Exemple #40
0
 /// <inheritdoc/>
 public override byte[] SignHash(byte[] hash, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
 {
     // Key Vault's API is known to use CA(false) everywhere. This should not deadlock.
     // See https://msdn.microsoft.com/en-us/magazine/mt238404.aspx ("The Blocking Hack")
     return(SignHashAsync(hash, hashAlgorithm, padding).GetAwaiter().GetResult());
 }
 protected abstract ISignValue SignByPrivateKeyInternal(ArraySegment <byte> buffer, HashAlgorithmName hashAlgorithmName, RSASignaturePadding padding, CancellationToken cancellationToken);
Exemple #42
0
        /// <inheritdoc/>
        public async Task <byte[]> SignHashAsync(byte[] hash, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
        {
            CheckDisposed();

            // Key Vault only supports PKCSv1 padding
            if (padding.Mode != RSASignaturePaddingMode.Pkcs1)
            {
                throw new CryptographicException("Unsupported padding mode");
            }

            try
            {
                return(await context.SignDigestAsync(hash, hashAlgorithm).ConfigureAwait(false));
            }
            catch (Exception e)
            {
                throw new CryptographicException("Error calling Key Vault", e);
            }
        }
 public virtual ISignValue SignByPrivateKey(ArraySegment <byte> buffer, RSASignaturePadding padding)
 {
     return(SignByPrivateKey(buffer, HashAlgorithmName.MD5, padding));
 }
 public override byte[] SignHash(byte[] hash, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding);
Exemple #45
0
 public override byte[] SignHash(byte[] hash, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
 {
     throw new NotImplementedException(SR.WorkInProgress);
 }
        public override byte[] SignHash(
            byte[] hash,
            HashAlgorithmName hashAlgorithm,
            RSASignaturePadding padding)
        {
            if (hash == null)
                throw new ArgumentNullException(nameof(hash));
            if (string.IsNullOrEmpty(hashAlgorithm.Name))
                throw HashAlgorithmNameNullOrEmpty();
            if (padding == null)
                throw new ArgumentNullException(nameof(padding));
            if (padding != RSASignaturePadding.Pkcs1)
                throw PaddingModeNotSupported();

            return SignHash(hash, GetAlgorithmId(hashAlgorithm));
        }
Exemple #47
0
 public virtual bool VerifyHash(byte[] hash, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { throw DerivedClassMustOverride(); }
Exemple #48
0
 protected override byte[] SignHash(RSA rsa, byte[] hash, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) =>
 rsa.SignHash(hash, hashAlgorithm, padding);
Exemple #49
0
        public override byte[] SignHash(byte[] hash, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
        {
            if (hash == null)
            {
               throw new ArgumentNullException("hash");
            }
            if (String.IsNullOrEmpty(hashAlgorithm.Name))
            {
                throw new ArgumentException(SR.GetString(SR.Cryptography_HashAlgorithmNameNullOrEmpty), "hashAlgorithm");
            } 
            if (padding == null)
            {
                throw new ArgumentNullException("padding");
            }

            // Keep a local copy of the key.
            CngKey key = Key;
            SafeNCryptKeyHandle keyHandle = key.Handle;

            if (padding == RSASignaturePadding.Pkcs1)
            {
                return NCryptNative.SignHashPkcs1(keyHandle, hash, hashAlgorithm.Name);
            }
            else if (padding == RSASignaturePadding.Pss)
            {
                return NCryptNative.SignHashPss(keyHandle, hash, hashAlgorithm.Name, hash.Length);
            }
            else
            {
                 // no other padding possibilities at present, but we might version independently from more being added.
                 throw new CryptographicException(SR.GetString(SR.Cryptography_UnsupportedPaddingMode));

            }
        }
Exemple #50
0
 protected override bool VerifyHash(RSA rsa, byte[] hash, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) =>
 rsa.VerifyHash(hash, signature, hashAlgorithm, padding);
Exemple #51
0
        /// <inheritdoc/>
        public override bool VerifyHash(byte[] hash, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
        {
            CheckDisposed();

            // Verify can be done locally using the public key
            return(publicKey.VerifyHash(hash, signature, hashAlgorithm, padding));
        }
Exemple #52
0
        /// <summary>
        /// Computes the signature for the specified hash value by encrypting it with the private key using a certificate with a pin.
        /// https://stackoverflow.com/questions/42626742/how-can-i-set-pin-for-a-x509certificate2-programmatically
        /// </summary>
        /// <param name="data">Data (not hash) to be signed</param>
        /// <param name="privateKey">The private key used for signing</param>
        /// <param name="hashAlgorithm">The hash algorithm used in hashing the data before signing</param>
        /// <param name="padding">The padding that will be used in the signature</param>
        /// <param name="pin">The private key pin</param>
        /// <returns>Return signed hash as byte array, or null if fails</returns>
        /// <exception cref="ArgumentException">There is null in the parameters or one of the parameters empty</exception>
        /// <exception cref="CryptographicException">The cryptographic service provider (CSP) cannot be acquired.-or- The parameters parameter has missing fields. -or- The padding mode is not supported. -or- The certificate context is invalid. -or- wrong pin has been inputed.</exception>
        public static byte[] SignHash(byte[] hash, X509Certificate2 privateKey, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding, string pin)
        {
            try
            {
                RSA    rsa    = privateKey.GetRSAPrivateKey();
                RSACng rsaCng = rsa as RSACng;
                if (rsaCng != null)
                {
                    // Set the PIN, an explicit null terminator is required to this Unicode/UCS-2 string.
                    byte[] propertyBytes;

                    if (pin[pin.Length - 1] == '\0')
                    {
                        propertyBytes = Encoding.Unicode.GetBytes(pin);
                    }
                    else
                    {
                        propertyBytes = new byte[Encoding.Unicode.GetByteCount(pin) + 2];
                        Encoding.Unicode.GetBytes(pin, 0, pin.Length, propertyBytes, 0);
                    }

                    const string NCRYPT_PIN_PROPERTY = "SmartCardPin";

                    CngProperty pinProperty = new CngProperty(
                        NCRYPT_PIN_PROPERTY,
                        propertyBytes,
                        CngPropertyOptions.None);

                    rsaCng.Key.SetProperty(pinProperty);
                    return(rsaCng.SignHash(hash, hashAlgorithm, padding));
                }
                throw new CryptographicException("The key is not compatible with Cryptography Next Generation (CNG)");
            }
            catch (ArgumentException ex)
            {
                throw ex;
            }
            catch (CryptographicException ex)
            {
                throw ex;
            }
        }
 public override bool VerifyHash(byte[] hash, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding);
Exemple #54
0
        private static bool VerifyRsa2048Sha256(ReadOnlySpan <byte> signature, ReadOnlySpan <byte> modulus,
                                                ReadOnlySpan <byte> exponent, ReadOnlySpan <byte> message, RSASignaturePadding padding)
        {
            try
            {
                var param = new RSAParameters {
                    Modulus = modulus.ToArray(), Exponent = exponent.ToArray()
                };

                using (var rsa = RSA.Create(param))
                {
                    return(rsa.VerifyData(message, signature, HashAlgorithmName.SHA256, padding));
                }
            }
            catch (CryptographicException)
            {
                return(false);
            }
        }
Exemple #55
0
        public override bool VerifyHash(
            byte[] hash,
            byte[] signature,
            HashAlgorithmName hashAlgorithm,
            RSASignaturePadding padding)
        {
            if (hash == null)
                throw new ArgumentNullException("hash");
            if (string.IsNullOrEmpty(hashAlgorithm.Name))
                throw HashAlgorithmNameNullOrEmpty();
            if (padding == null)
                throw new ArgumentNullException("padding");
            if (padding != RSASignaturePadding.Pkcs1)
                throw PaddingModeNotSupported();

            return VerifyHash(hash, signature, hashAlgorithm);
        }
Exemple #56
0
 protected override byte[] SignData(RSA rsa, byte[] data, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) =>
 rsa.SignData(data, hashAlgorithm, padding);