コード例 #1
0
        public override Jwk WrapKey(Jwk?staticKey, JwtObject header, Span <byte> destination)
        {
            if (staticKey != null)
            {
                ThrowHelper.ThrowArgumentException_StaticKeyNotSupported();
            }

            ReadOnlySpan <byte> bytes = Key.AsSpan();

            return(SymmetricJwk.FromSpan(bytes, false));
        }
コード例 #2
0
        /// <inheritsdoc />
        public override Jwk WrapKey(Jwk?staticKey, JwtObject header, Span <byte> destination)
        {
            if (_disposed)
            {
                ThrowHelper.ThrowObjectDisposedException(GetType());
            }

            var         cek   = CreateSymmetricKey(EncryptionAlgorithm, staticKey);
            Span <byte> nonce = stackalloc byte[IVSize];
            Span <byte> tag   = stackalloc byte[TagSize];

            using (var aesGcm = new AesGcm(Key.AsSpan()))
            {
                aesGcm.Encrypt(nonce, cek.AsSpan(), destination, tag);

                header.Add(new JwtProperty(HeaderParameters.IVUtf8, Base64Url.Encode(nonce)));
                header.Add(new JwtProperty(HeaderParameters.TagUtf8, Base64Url.Encode(tag)));
            }

            return(cek);
        }
コード例 #3
0
        /// <inheritsdoc />
        public override bool TryUnwrapKey(ReadOnlySpan <byte> keyBytes, Span <byte> destination, JwtHeader header, out int bytesWritten)
        {
            if (_disposed)
            {
                ThrowHelper.ThrowObjectDisposedException(GetType());
            }

            var encodedIV  = header.IV;
            var encodedTag = header.Tag;

            if (encodedIV is null)
            {
                ThrowHelper.ThrowJwtDescriptorException_HeaderIsRequired(HeaderParameters.IVUtf8);
            }

            if (encodedTag is null)
            {
                ThrowHelper.ThrowJwtDescriptorException_HeaderIsRequired(HeaderParameters.TagUtf8);
            }

            Span <byte> nonce = stackalloc byte[Base64Url.GetArraySizeRequiredToDecode(encodedIV.Length)];
            Span <byte> tag   = stackalloc byte[Base64Url.GetArraySizeRequiredToDecode(encodedTag.Length)];

            try
            {
                Base64Url.Decode(encodedIV, nonce);
                Base64Url.Decode(encodedTag, tag);
                using var aesGcm = new AesGcm(Key.AsSpan());
                aesGcm.Decrypt(nonce, keyBytes, tag, destination);
                bytesWritten = destination.Length;

                return(true);
            }
            catch (CryptographicException)
            {
                return(ThrowHelper.TryWriteError(out bytesWritten));
            }
        }