Exemple #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,
            });
        }
Exemple #2
0
        public WrapResult WrapKey(KeyWrapAlgorithm algorithm, byte[] key, CancellationToken cancellationToken)
        {
            Argument.AssertNotNull(key, nameof(key));

            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 encryptor = AesKw.CreateEncryptor(sizedKey);

            byte[] encryptedKey = encryptor.TransformFinalBlock(key, 0, key.Length);
            return(new WrapResult
            {
                Algorithm = algorithm,
                EncryptedKey = encryptedKey,
                KeyId = _jwk.Id,
            });
        }