Beispiel #1
0
 public AzureKeyVaultMaterializedConfiguration(KeyVaultClient client, X509Certificate2 publicCertificate,
                                               KeyBundle key, Crypto.HashAlgorithmName fileDigestAlgorithm, Crypto.HashAlgorithmName pkcsDigestAlgorithm)
 {
     Client              = client;
     Key                 = key;
     PublicCertificate   = publicCertificate;
     FileDigestAlgorithm = fileDigestAlgorithm;
     PkcsDigestAlgorithm = pkcsDigestAlgorithm;
 }
        public Rfc3161TimestampRequest(
            byte[] messageHash,
            HashAlgorithmName hashAlgorithm,
            Oid requestedPolicyId              = null,
            byte[] nonce                       = null,
            bool requestSignerCertificates     = false,
            X509ExtensionCollection extensions = null)
        {
            if (messageHash == null)
            {
                throw new ArgumentNullException(nameof(messageHash));
            }

            int    expectedSize;
            string algorithmIdentifier;

            if (!ResolveAlgorithm(hashAlgorithm, out expectedSize, out algorithmIdentifier))
            {
                throw new ArgumentOutOfRangeException(
                          nameof(hashAlgorithm),
                          hashAlgorithm,
                          "Hash algorithm is not supported by this method");
            }

            if (messageHash.Length != expectedSize)
            {
                throw new ArgumentException("Hash is not the correct size for the identified algorithm", nameof(messageHash));
            }

            if (requestedPolicyId != null && !Rfc3161TimestampUtils.IsLegalOid(requestedPolicyId.Value))
            {
                throw new ArgumentException("Value is not a legal object identifier", nameof(requestedPolicyId));
            }

            if (nonce != null && nonce.Length == 0)
            {
                throw new ArgumentException("Nonce must be null or non-empty", nameof(nonce));
            }

            var data = new DataType
            {
                _version                  = 1,
                _hash                     = (byte[])messageHash.Clone(),
                _hashAlgorithm            = OpportunisticOid(algorithmIdentifier),
                _nonce                    = (byte[])nonce?.Clone(),
                _requestSignerCertificate = requestSignerCertificates,
                _extensions               = Rfc3161TimestampTokenInfo.ShallowCopy(extensions, preserveNull: true),
            };

            if (requestedPolicyId != null)
            {
                data._requestedPolicyId = new Oid(requestedPolicyId.Value, requestedPolicyId.FriendlyName);
            }

            RawData = Encode(data);
        }
Beispiel #3
0
 protected virtual byte[] HashData(Stream data, HashAlgorithmName hashAlgorithm)
 {
     throw DerivedClassMustOverride();
 }
Beispiel #4
0
        public override bool VerifyHash(ReadOnlySpan <byte> hash, ReadOnlySpan <byte> signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
        {
            if (string.IsNullOrEmpty(hashAlgorithm.Name))
            {
                throw HashAlgorithmNameNullOrEmpty();
            }
            if (padding == null)
            {
                throw new ArgumentNullException(nameof(padding));
            }

            if (padding == RSASignaturePadding.Pkcs1)
            {
                int           algorithmNid = GetAlgorithmNid(hashAlgorithm);
                SafeRsaHandle rsa          = GetKey();
                return(Interop.Crypto.RsaVerify(algorithmNid, hash, signature, rsa));
            }
            else if (padding == RSASignaturePadding.Pss)
            {
                RsaPaddingProcessor processor = RsaPaddingProcessor.OpenProcessor(hashAlgorithm);
                SafeRsaHandle       rsa       = GetKey();

                int requiredBytes = Interop.Crypto.RsaSize(rsa);

                if (signature.Length != requiredBytes)
                {
                    return(false);
                }

                if (hash.Length != processor.HashLength)
                {
                    return(false);
                }

                byte[]      rented    = CryptoPool.Rent(requiredBytes);
                Span <byte> unwrapped = new Span <byte>(rented, 0, requiredBytes);

                try
                {
                    int ret = Interop.Crypto.RsaVerificationPrimitive(signature, unwrapped, rsa);

                    CheckReturn(ret);

                    Debug.Assert(
                        ret == requiredBytes,
                        $"RSA_private_encrypt returned {ret} when {requiredBytes} was expected");

                    return(processor.VerifyPss(hash, unwrapped, KeySize));
                }
                finally
                {
                    CryptoPool.Return(rented, requiredBytes);
                }
            }

            throw PaddingModeNotSupported();
        }
Beispiel #5
0
 protected override byte[] HashData(Stream data, HashAlgorithmName hashAlgorithm) =>
 AsymmetricAlgorithmHelpers.HashData(data, hashAlgorithm);
        private static unsafe void PHash(
            HashAlgorithmName algorithmName,
            ReadOnlySpan <byte> secret,
            ReadOnlySpan <byte> prfLabel,
            ReadOnlySpan <byte> prfSeed,
            int hashOutputSize,
            Span <byte> ret)
        {
            // https://tools.ietf.org/html/rfc4346#section-5
            //
            // P_hash(secret, seed) = HMAC_hash(secret, A(1) + seed) +
            //                        HMAC_hash(secret, A(2) + seed) +
            //                        HMAC_hash(secret, A(3) + seed) + ...
            //
            // A(0) = seed
            // A(i) = HMAC_hash(secret, A(i-1))
            //
            // This is called via PRF, which turns (label || seed) into seed.

            byte[] secretTmp = new byte[secret.Length];

            // Keep secretTmp pinned the whole time it has a secret in it, so it
            // doesn't get copied around during heap compaction.
            fixed(byte *pinnedSecretTmp = secretTmp)
            {
                secret.CopyTo(secretTmp);

                try
                {
                    Span <byte> retSpan = ret;

                    using (IncrementalHash hasher = IncrementalHash.CreateHMAC(algorithmName, secretTmp))
                    {
                        Span <byte> a = stackalloc byte[hashOutputSize];
                        Span <byte> p = stackalloc byte[hashOutputSize];

                        // A(1)
                        hasher.AppendData(prfLabel);
                        hasher.AppendData(prfSeed);

                        if (!hasher.TryGetHashAndReset(a, out int bytesWritten) || bytesWritten != hashOutputSize)
                        {
                            throw new CryptographicException();
                        }

                        while (true)
                        {
                            // HMAC_hash(secret, A(i) || seed) => p
                            hasher.AppendData(a);
                            hasher.AppendData(prfLabel);
                            hasher.AppendData(prfSeed);

                            if (!hasher.TryGetHashAndReset(p, out bytesWritten) || bytesWritten != hashOutputSize)
                            {
                                throw new CryptographicException();
                            }

                            int len = Math.Min(p.Length, retSpan.Length);

                            p.Slice(0, len).CopyTo(retSpan);
                            retSpan = retSpan.Slice(len);

                            if (retSpan.Length == 0)
                            {
                                return;
                            }

                            // Build the next A(i)
                            hasher.AppendData(a);

                            if (!hasher.TryGetHashAndReset(a, out bytesWritten) || bytesWritten != hashOutputSize)
                            {
                                throw new CryptographicException();
                            }
                        }
                    }
                }
                finally
                {
                    Array.Clear(secretTmp, 0, secretTmp.Length);
                }
            }
        }
Beispiel #7
0
 public Rfc2898DeriveBytes(string password, byte[] salt, int iterations, HashAlgorithmName hashAlgorithm)
     : this(Encoding.UTF8.GetBytes(password), salt, iterations, hashAlgorithm)
 {
 }
Beispiel #8
0
 protected override byte[] HashData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm)
 {
     return(CngAsymmetricAlgorithmCore.HashData(data, offset, count, hashAlgorithm));
 }
Beispiel #9
0
        public virtual bool TrySignHash(ReadOnlySpan <byte> hash, Span <byte> destination, HashAlgorithmName hashAlgorithm, out int bytesWritten)
        {
            byte[] result = SignHash(hash.ToArray(), hashAlgorithm);

            if (destination.Length >= result.Length)
            {
                new ReadOnlySpan <byte>(result).CopyTo(destination);
                bytesWritten = result.Length;
                return(true);
            }

            bytesWritten = 0;
            return(false);
        }
Beispiel #10
0
        protected virtual bool TryHashData(ReadOnlySpan <byte> data, Span <byte> destination, HashAlgorithmName hashAlgorithm, out int bytesWritten)
        {
            byte[] result;
            byte[] array = ArrayPool <byte> .Shared.Rent(data.Length);

            try
            {
                data.CopyTo(array);
                result = HashData(array, 0, data.Length, hashAlgorithm);
            }
            finally
            {
                Array.Clear(array, 0, data.Length);
                ArrayPool <byte> .Shared.Return(array);
            }

            if (destination.Length >= result.Length)
            {
                new ReadOnlySpan <byte>(result).CopyTo(destination);
                bytesWritten = result.Length;
                return(true);
            }

            bytesWritten = 0;
            return(false);
        }
Beispiel #11
0
 public virtual bool VerifyHash(byte[] hash, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
 {
     throw DerivedClassMustOverride();
 }
Beispiel #12
0
 public virtual bool VerifyHash(ReadOnlySpan <byte> hash, ReadOnlySpan <byte> signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) =>
 VerifyHash(hash.ToArray(), signature.ToArray(), hashAlgorithm, padding);
Beispiel #13
0
        public virtual bool VerifyData(ReadOnlySpan <byte> data, ReadOnlySpan <byte> signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
        {
            if (string.IsNullOrEmpty(hashAlgorithm.Name))
            {
                throw HashAlgorithmNameNullOrEmpty();
            }
            if (padding == null)
            {
                throw new ArgumentNullException(nameof(padding));
            }

            for (int i = 256; ; i = checked (i * 2))
            {
                int    hashLength = 0;
                byte[] hash       = ArrayPool <byte> .Shared.Rent(i);

                try
                {
                    if (TryHashData(data, hash, hashAlgorithm, out hashLength))
                    {
                        return(VerifyHash(new ReadOnlySpan <byte>(hash, 0, hashLength), signature, hashAlgorithm, padding));
                    }
                }
                finally
                {
                    Array.Clear(hash, 0, hashLength);
                    ArrayPool <byte> .Shared.Return(hash);
                }
            }
        }
Beispiel #14
0
        public virtual bool TrySignData(ReadOnlySpan <byte> data, Span <byte> destination, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding, out int bytesWritten)
        {
            if (string.IsNullOrEmpty(hashAlgorithm.Name))
            {
                throw HashAlgorithmNameNullOrEmpty();
            }
            if (padding == null)
            {
                throw new ArgumentNullException(nameof(padding));
            }

            if (TryHashData(data, destination, hashAlgorithm, out int hashLength) &&
                TrySignHash(destination.Slice(0, hashLength), destination, hashAlgorithm, padding, out bytesWritten))
            {
                return(true);
            }

            bytesWritten = 0;
            return(false);
        }
Beispiel #15
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));
        }
Beispiel #16
0
            public override bool TrySignHash(ReadOnlySpan <byte> hash, Span <byte> destination, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding, out int bytesWritten)
            {
                if (string.IsNullOrEmpty(hashAlgorithm.Name))
                {
                    throw HashAlgorithmNameNullOrEmpty();
                }
                if (padding == null)
                {
                    throw new ArgumentNullException(nameof(padding));
                }

                RsaPaddingProcessor processor = null;

                if (padding.Mode == RSASignaturePaddingMode.Pss)
                {
                    processor = RsaPaddingProcessor.OpenProcessor(hashAlgorithm);
                }
                else if (padding != RSASignaturePadding.Pkcs1)
                {
                    throw new CryptographicException(SR.Cryptography_InvalidPaddingMode);
                }

                SecKeyPair keys = GetKeys();

                if (keys.PrivateKey == null)
                {
                    throw new CryptographicException(SR.Cryptography_CSP_NoPrivateKey);
                }

                int keySize = KeySize;
                int rsaSize = RsaPaddingProcessor.BytesRequiredForBitCount(keySize);

                if (processor == null)
                {
                    Interop.AppleCrypto.PAL_HashAlgorithm palAlgId =
                        PalAlgorithmFromAlgorithmName(hashAlgorithm, out int expectedSize);

                    if (hash.Length != expectedSize)
                    {
                        // Windows: NTE_BAD_DATA ("Bad Data.")
                        // OpenSSL: RSA_R_INVALID_MESSAGE_LENGTH ("invalid message length")
                        throw new CryptographicException(
                                  SR.Format(
                                      SR.Cryptography_BadHashSize_ForAlgorithm,
                                      hash.Length,
                                      expectedSize,
                                      hashAlgorithm.Name));
                    }

                    if (destination.Length < rsaSize)
                    {
                        bytesWritten = 0;
                        return(false);
                    }

                    return(Interop.AppleCrypto.TryGenerateSignature(
                               keys.PrivateKey,
                               hash,
                               destination,
                               palAlgId,
                               out bytesWritten));
                }

                Debug.Assert(padding.Mode == RSASignaturePaddingMode.Pss);

                if (destination.Length < rsaSize)
                {
                    bytesWritten = 0;
                    return(false);
                }

                byte[] rented = ArrayPool <byte> .Shared.Rent(rsaSize);

                Span <byte> buf = new Span <byte>(rented, 0, rsaSize);

                processor.EncodePss(hash, buf, keySize);

                try
                {
                    return(Interop.AppleCrypto.TryRsaSignaturePrimitive(keys.PrivateKey, buf, destination, out bytesWritten));
                }
                finally
                {
                    CryptographicOperations.ZeroMemory(buf);
                    ArrayPool <byte> .Shared.Return(rented);
                }
            }
Beispiel #17
0
            public override bool VerifyHash(ReadOnlySpan <byte> hash, ReadOnlySpan <byte> signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
            {
                if (string.IsNullOrEmpty(hashAlgorithm.Name))
                {
                    throw HashAlgorithmNameNullOrEmpty();
                }
                if (padding == null)
                {
                    throw new ArgumentNullException(nameof(padding));
                }

                if (padding == RSASignaturePadding.Pkcs1)
                {
                    Interop.AppleCrypto.PAL_HashAlgorithm palAlgId =
                        PalAlgorithmFromAlgorithmName(hashAlgorithm, out int expectedSize);
                    return(Interop.AppleCrypto.VerifySignature(GetKeys().PublicKey, hash, signature, palAlgId));
                }
                else if (padding.Mode == RSASignaturePaddingMode.Pss)
                {
                    RsaPaddingProcessor processor = RsaPaddingProcessor.OpenProcessor(hashAlgorithm);
                    SafeSecKeyRefHandle publicKey = GetKeys().PublicKey;

                    int keySize = KeySize;
                    int rsaSize = RsaPaddingProcessor.BytesRequiredForBitCount(keySize);

                    if (signature.Length != rsaSize)
                    {
                        return(false);
                    }

                    if (hash.Length != processor.HashLength)
                    {
                        return(false);
                    }

                    byte[] rented = ArrayPool <byte> .Shared.Rent(rsaSize);

                    Span <byte> unwrapped = new Span <byte>(rented, 0, rsaSize);

                    try
                    {
                        if (!Interop.AppleCrypto.TryRsaVerificationPrimitive(
                                publicKey,
                                signature,
                                unwrapped,
                                out int bytesWritten))
                        {
                            Debug.Fail($"TryRsaVerificationPrimitive with a pre-allocated buffer");
                            throw new CryptographicException();
                        }

                        Debug.Assert(bytesWritten == rsaSize);
                        return(processor.VerifyPss(hash, unwrapped, keySize));
                    }
                    finally
                    {
                        unwrapped.Clear();
                        ArrayPool <byte> .Shared.Return(rented);
                    }
                }

                throw new CryptographicException(SR.Cryptography_InvalidPaddingMode);
            }
Beispiel #18
0
 public virtual bool VerifyHash(ReadOnlySpan <byte> hash, ReadOnlySpan <byte> signature, HashAlgorithmName hashAlgorithm) =>
 VerifyHash(hash.ToArray(), signature.ToArray(), hashAlgorithm);
Beispiel #19
0
 protected override byte[] HashData(Stream data, HashAlgorithmName hashAlgorithm)
 {
     return(CngAsymmetricAlgorithmCore.HashData(data, hashAlgorithm));
 }
Beispiel #20
0
        public virtual bool TrySignData(ReadOnlySpan <byte> data, Span <byte> destination, HashAlgorithmName hashAlgorithm, out int bytesWritten)
        {
            if (string.IsNullOrEmpty(hashAlgorithm.Name))
            {
                throw HashAlgorithmNameNullOrEmpty();
            }

            if (TryHashData(data, destination, hashAlgorithm, out int hashLength) &&
                TrySignHash(destination.Slice(0, hashLength), destination, hashAlgorithm, out bytesWritten))
            {
                return(true);
            }

            bytesWritten = 0;
            return(false);
        }
 private static HashAlgorithm GetHashAlgorithm(HashAlgorithmName hashAlgorithm) =>
     hashAlgorithm.Name switch
     {
         "MD5" => MD5.Create(),
Beispiel #22
0
        public virtual bool VerifyData(ReadOnlySpan <byte> data, ReadOnlySpan <byte> signature, HashAlgorithmName hashAlgorithm)
        {
            if (string.IsNullOrEmpty(hashAlgorithm.Name))
            {
                throw HashAlgorithmNameNullOrEmpty();
            }

            for (int i = 512; ; i = checked (i * 2))
            {
                int    hashLength = 0;
                byte[] hash       = ArrayPool <byte> .Shared.Rent(i);

                try
                {
                    if (TryHashData(data, hash, hashAlgorithm, out hashLength))
                    {
                        return(VerifyHash(new ReadOnlySpan <byte>(hash, 0, hashLength), signature, hashAlgorithm));
                    }
                }
                finally
                {
                    Array.Clear(hash, 0, hashLength);
                    ArrayPool <byte> .Shared.Return(hash);
                }
            }
        }
Beispiel #23
0
 protected override byte[] HashData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm) =>
 AsymmetricAlgorithmHelpers.HashData(data, offset, count, hashAlgorithm);
Beispiel #24
0
 public abstract byte[] SignHash(byte[] hash, HashAlgorithmName hashAlgorithm);                   //=> throw DerivedClassMustOverride();
Beispiel #25
0
 protected override bool TryHashData(ReadOnlySpan <byte> data, Span <byte> destination, HashAlgorithmName hashAlgorithm, out int bytesWritten) =>
 AsymmetricAlgorithmHelpers.TryHashData(data, destination, hashAlgorithm, out bytesWritten);
Beispiel #26
0
 public abstract byte[] SignHash(byte[] hash, HashAlgorithmName hashAlgorithm);                   //=> throw DerivedClassMustOverride();
 public abstract bool VerifyHash(byte[] hash, byte[] signature, HashAlgorithmName hashAlgorithm); // => throw DerivedClassMustOverride();
Beispiel #27
0
 protected abstract byte[] HashData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm); // => throw DerivedClassMustOverride();
Beispiel #28
0
        protected abstract byte[] HashData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm); // => throw DerivedClassMustOverride();

        protected abstract byte[] HashData(Stream data, HashAlgorithmName hashAlgorithm);                        // => throw DerivedClassMustOverride();
Beispiel #29
0
 public static System.Security.Cryptography.IncrementalHash CreateHMAC(System.Security.Cryptography.HashAlgorithmName hashAlgorithm, byte[] key)
 {
     throw null;
 }
Beispiel #30
0
 protected virtual byte[] HashData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm)
 {
     throw DerivedClassMustOverride();
 }