Ejemplo n.º 1
0
        /// <summary>
        /// Gets the decrypting stream.
        /// </summary>
        /// <param name="output">The output.</param>
        /// <returns></returns>
        public override FinishingStream GetDecryptingStream(Stream output, Keyczar.KeyczarBase keyczar)
        {
            var alg = new AesManaged
            {
                Mode      = GetMode(),
                Key       = AesKeyBytes,
                Padding   = PaddingMode.PKCS7,
                BlockSize = BlockLength * 8
            };

            return(new DotNetSymmetricStream(alg, output, HmacKey.Maybe(h => h.HashLength, () => 0), encrypt: false));
        }
Ejemplo n.º 2
0
        private async Task ChangeHmacKey(HmacKey newKey)
        {
            if (_hmacKey != null)
            {
                await _hmacKey.DisposeAsync();
            }

            _hmacKey = newKey;
            byte[] keyBytes = await newKey.ExportKeyAsync();

            _hmacKeyLabel = $"({newKey.DigestAlgorithm.Name}) {Convert.ToHexString(keyBytes)}";
        }
Ejemplo n.º 3
0
        private async Task ImportHmacSha384()
        {
            byte[] keyBytes = GetInputBytes();

            try
            {
                HmacKey key = await GetSubtleCrypto().ImportHmacKeySha384Async(keyBytes);
                await ChangeHmacKey(key);
            }
            catch (Exception e)
            {
                _output = e.ToString();
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Gets the encrypting stream.
        /// </summary>
        /// <param name="output">The output.</param>
        /// <returns></returns>
        public override FinishingStream GetEncryptingStream(Stream output, Keyczar.KeyczarBase keyczar)
        {
            var alg = new AesManaged
            {
                Mode      = GetMode(),
                Key       = AesKeyBytes,
                Padding   = PaddingMode.PKCS7,
                BlockSize = BlockLength * 8
            };

            alg.GenerateIV();


            int hashlength = HmacKey.Maybe(h => h.HashLength, () => 0);

            return(new DotNetSymmetricStream(alg, output, hashlength, encrypt: true));
        }
Ejemplo n.º 5
0
        public byte[] DeriveKeyMaterial(CngKey otherPartyPublicKey)
        {
            Contract.Ensures(Contract.Result <byte[]>() != null);
            Contract.Assert(m_kdf >= ECDiffieHellmanKeyDerivationFunction.Hash &&
                            m_kdf <= ECDiffieHellmanKeyDerivationFunction.Tls);

            if (otherPartyPublicKey == null)
            {
                throw new ArgumentNullException("otherPartyPublicKey");
            }
            if (otherPartyPublicKey.AlgorithmGroup != CngAlgorithmGroup.ECDiffieHellman)
            {
                throw new ArgumentException(SR.GetString(SR.Cryptography_ArgECDHRequiresECDHKey), "otherPartyPublicKey");
            }
            if (otherPartyPublicKey.KeySize != KeySize)
            {
                throw new ArgumentException(SR.GetString(SR.Cryptography_ArgECDHKeySizeMismatch), "otherPartyPublicKey");
            }

            NCryptNative.SecretAgreementFlags flags =
                UseSecretAgreementAsHmacKey ? NCryptNative.SecretAgreementFlags.UseSecretAsHmacKey : NCryptNative.SecretAgreementFlags.None;

            // We require access to the handles for generating key material. This is safe since we will never
            // expose these handles to user code
            new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert();

            // This looks horribly wrong - but accessing the handle property actually returns a duplicate handle, which
            // we need to dispose of - otherwise, we're stuck keepign the resource alive until the GC runs.  This explicitly
            // is not disposing of the handle underlying the key dispite what the syntax looks like.
            using (SafeNCryptKeyHandle localKey = Key.Handle)
                using (SafeNCryptKeyHandle otherKey = otherPartyPublicKey.Handle) {
                    CodeAccessPermission.RevertAssert();

                    //
                    // Generating key material is a two phase process.
                    //   1. Generate the secret agreement
                    //   2. Pass the secret agreement through a KDF to get key material
                    //

                    using (SafeNCryptSecretHandle secretAgreement = NCryptNative.DeriveSecretAgreement(localKey, otherKey)) {
                        if (KeyDerivationFunction == ECDiffieHellmanKeyDerivationFunction.Hash)
                        {
                            byte[] secretAppend  = SecretAppend == null ? null : SecretAppend.Clone() as byte[];
                            byte[] secretPrepend = SecretPrepend == null ? null : SecretPrepend.Clone() as byte[];

                            return(NCryptNative.DeriveKeyMaterialHash(secretAgreement,
                                                                      HashAlgorithm.Algorithm,
                                                                      secretPrepend,
                                                                      secretAppend,
                                                                      flags));
                        }
                        else if (KeyDerivationFunction == ECDiffieHellmanKeyDerivationFunction.Hmac)
                        {
                            byte[] hmacKey       = HmacKey == null ? null : HmacKey.Clone() as byte[];
                            byte[] secretAppend  = SecretAppend == null ? null : SecretAppend.Clone() as byte[];
                            byte[] secretPrepend = SecretPrepend == null ? null : SecretPrepend.Clone() as byte[];

                            return(NCryptNative.DeriveKeyMaterialHmac(secretAgreement,
                                                                      HashAlgorithm.Algorithm,
                                                                      hmacKey,
                                                                      secretPrepend,
                                                                      secretAppend,
                                                                      flags));
                        }
                        else
                        {
                            Debug.Assert(KeyDerivationFunction == ECDiffieHellmanKeyDerivationFunction.Tls, "Unknown KDF");

                            byte[] label = Label == null ? null : Label.Clone() as byte[];
                            byte[] seed  = Seed == null ? null : Seed.Clone() as byte[];

                            if (label == null || seed == null)
                            {
                                throw new InvalidOperationException(SR.GetString(SR.Cryptography_TlsRequiresLabelAndSeed));
                            }

                            return(NCryptNative.DeriveKeyMaterialTls(secretAgreement, label, seed, flags));
                        }
                    }
                }
        }