Пример #1
0
        public override WrapResult WrapKey(KeyWrapAlgorithm algorithm, byte[] key, CancellationToken cancellationToken)
        {
            Argument.AssertNotNull(key, nameof(key));

            ThrowIfTimeInvalid();

            int algorithmKeySizeBytes = algorithm.GetKeySizeInBytes();

            if (algorithmKeySizeBytes == 0)
            {
                KeysEventSource.Singleton.AlgorithmNotSupported(nameof(WrapKey), algorithm);
                return(null);
            }

            int keySizeBytes = GetKeySizeInBytes();

            if (keySizeBytes < algorithmKeySizeBytes)
            {
                throw new ArgumentException($"Key wrap algorithm {algorithm} key size {algorithmKeySizeBytes} is greater than the underlying key size {keySizeBytes}");
            }

            byte[] sizedKey = (keySizeBytes == algorithmKeySizeBytes) ? KeyMaterial.K : KeyMaterial.K.Take(algorithmKeySizeBytes);

            using ICryptoTransform encryptor = AesKw.CreateEncryptor(sizedKey);

            byte[] encryptedKey = encryptor.TransformFinalBlock(key, 0, key.Length);
            return(new WrapResult
            {
                Algorithm = algorithm,
                EncryptedKey = encryptedKey,
                KeyId = KeyMaterial.Id,
            });
        }
Пример #2
0
        public UnwrapResult UnwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, CancellationToken cancellationToken)
        {
            Argument.AssertNotNull(encryptedKey, nameof(encryptedKey));

            int algorithmKeySizeBytes = algorithm.GetKeySizeInBytes();

            if (algorithmKeySizeBytes == 0)
            {
                // TODO: Log that we don't support the algorithm locally.
                return(null);
            }

            int keySizeBytes = GetKeySizeInBytes();

            if (keySizeBytes < algorithmKeySizeBytes)
            {
                throw new ArgumentException($"Key wrap algorithm {algorithm} key size {algorithmKeySizeBytes} is greater than the underlying key size {keySizeBytes}");
            }

            byte[] sizedKey = (keySizeBytes == algorithmKeySizeBytes) ? _jwk.K : _jwk.K.Take(algorithmKeySizeBytes);

            using ICryptoTransform decryptor = AesKw.CreateDecryptor(sizedKey);

            byte[] key = decryptor.TransformFinalBlock(encryptedKey, 0, encryptedKey.Length);
            return(new UnwrapResult
            {
                Algorithm = algorithm,
                Key = key,
                KeyId = _jwk.Id,
            });
        }