示例#1
0
 public void Encrypt_throws_on_invalid_key_length()
 {
     Assert.That(
         () => AesGcm.Encrypt(key: new byte[13],
                              plaintext: new byte[16],
                              iv: new byte[12],
                              authData: new byte[0]),
         ExceptionsTest.ThrowsInvalidOpeationWithMessage("key must"));
 }
示例#2
0
 public void Decrypt_throws_on_invalid_iv_length()
 {
     Assert.That(
         () => AesGcm.Decrypt(key: new byte[32],
                              ciphertext: new byte[16],
                              iv: new byte[13],
                              authData: new byte[0]),
         ExceptionsTest.ThrowsInvalidOpeationWithMessage("iv must"));
 }
示例#3
0
        private byte[] DecryptBuffer(byte[] encryptedInput, byte[] nonce, byte[] gcmtag, int keyinfo)
        {
            byte[] result = new byte[encryptedInput.Length];

            using (var authenticatedAesCng = new AesGcm(keyinfo == 1 ? _key : _altKey)) {
                authenticatedAesCng.Decrypt(nonce, encryptedInput, gcmtag, result);
            }
            return(result);
        }
示例#4
0
        static (byte[] CipherText, byte[] Tag) EncryptGCM(string text, byte[] key, byte[] nonce, byte[] associatedData = null)
        {
            var byteText   = Encoding.ASCII.GetBytes(text);
            var tag        = new byte[16];
            var cipherText = new byte[byteText.Length];

            using var gcm = new AesGcm(key);
            gcm.Encrypt(nonce, byteText, cipherText, tag, associatedData);
            return(cipherText, tag);
        }
        public void GHash_returns_hash(TestCase tc)
        {
            var hash = AesGcm.GHash(tc.HashKey,
                                    tc.AuthData,
                                    tc.AuthData.Length,
                                    tc.Ciphertext,
                                    tc.Ciphertext.Length);

            Assert.Equal(tc.GHash, hash);
        }
示例#6
0
        /// <inheritdoc />
        public override void Encrypt(ReadOnlySpan <byte> plaintext, ReadOnlySpan <byte> nonce, ReadOnlySpan <byte> associatedData, Span <byte> ciphertext, Span <byte> authenticationTag)
        {
            if (_disposed)
            {
                ThrowHelper.ThrowObjectDisposedException(GetType());
            }

            using var aes = new AesGcm(_key.K);
            aes.Encrypt(nonce, plaintext, ciphertext, authenticationTag, associatedData);
        }
    public void TryUsingAesGcm()
    {
        // Super bad crypto. Just here to demonstrate that it does not explode.
        var    key = new byte[16];
        AesGcm gcm = new AesGcm(key);

        byte[] plaintext = new byte[1], ciphertext = new byte[1];
        byte[] nonce     = new byte[12], tag = new byte[16];
        gcm.Encrypt(nonce, plaintext, ciphertext, tag);
    }
示例#8
0
        public static (byte[], byte[]) GCM_Encrypt(byte[] key, byte[] nonce, byte[] input, byte[] associatedData)
        {
            var tag    = new byte[16];
            var output = new byte[input.Length];

            using var aesGcm = new AesGcm(key);
            aesGcm.Encrypt(nonce, input, output, tag, associatedData);

            return(output, tag);
        }
示例#9
0
        public GcmAuthenticatedCryptographicTransform(byte[] key, TransformMode mode)
        {
            TransformMode = mode;

#if NETSTANDARD2_1_OR_GREATER || NETCOREAPP3_1_OR_GREATER
            _gcm = new AesGcm(key);
#else
            _gcm = new AesGcmWindows(key);
#endif
        }
示例#10
0
        /// <summary>
        /// Encrypts data using AES-GCM, then packages with the authentication code and nonce.
        /// </summary>
        /// <param name="plainblob">The plainblob to encrypt.</param>
        /// <param name="overrideKey">An optional key to override the default key.</param>
        /// <returns>The secure package.</returns>
        public byte[] Encrypt(byte[] plainblob, byte[]?overrideKey = null)
        {
            var nonce      = SecureRandomGenerator.GetBytes(NONCE_SIZE);
            var cipherblob = new byte[plainblob.Length];
            var tag        = new byte[TAG_SIZE];

            using var aes = new AesGcm(overrideKey ?? key);
            aes.Encrypt(nonce, plainblob, cipherblob, tag);
            return(nonce.Concat(tag).Concat(cipherblob).ToArray());
        }
示例#11
0
 public void Decrypt_throws_on_modified_ciphertext()
 {
     foreach (var i in TestCases)
     {
         // Change the first byte of the ciphertext
         var modified = Modified(i.CiphertextWithTag, 0);
         Assert.That(() => AesGcm.Decrypt(i.Key, modified, i.Iv, i.AuthData),
                     ExceptionsTest.ThrowsInvalidOpeationWithMessage("auth tag"));
     }
 }
        public MemoryStream Encrypt(MemoryStream unencryptedStream, bool leaveStreamOpen = false)
        {
            Guard.AgainstNullOrEmpty(unencryptedStream, nameof(unencryptedStream));

            using var aes = new AesGcm(_key.Span);

            var length = (int)unencryptedStream.Length;

            (var buffer, var returnBuffer) = unencryptedStream.GetSafeBuffer(length);

            // Slicing Version
            // Rented arrays sizes are minimums, not guarantees.
            // Need to perform extra work managing slices to keep the byte sizes correct but the memory allocations are lower by 200%
            var encryptedBytes = _pool.Rent(length);
            var tag            = _pool.Rent(AesGcm.TagByteSizes.MaxSize);   // MaxSize = 16
            var nonce          = _pool.Rent(AesGcm.NonceByteSizes.MaxSize); // MaxSize = 12

            _rng.GetBytes(nonce, 0, AesGcm.NonceByteSizes.MaxSize);

            aes.Encrypt(
                nonce.AsSpan().Slice(0, AesGcm.NonceByteSizes.MaxSize),
                buffer.Slice(0, length),
                encryptedBytes.AsSpan().Slice(0, length),
                tag.AsSpan().Slice(0, AesGcm.TagByteSizes.MaxSize));

            // Prefix ciphertext with nonce and tag, since they are fixed length and it will simplify decryption.
            // Our pattern: Nonce Tag Cipher
            // Other patterns people use: Nonce Cipher Tag // couldn't find a solid source.
            var encryptedStream = new MemoryStream(new byte[AesGcm.NonceByteSizes.MaxSize + AesGcm.TagByteSizes.MaxSize + length]);

            using (var binaryWriter = new BinaryWriter(encryptedStream, Encoding.UTF8, true))
            {
                binaryWriter.Write(nonce, 0, AesGcm.NonceByteSizes.MaxSize);
                binaryWriter.Write(tag, 0, AesGcm.TagByteSizes.MaxSize);
                binaryWriter.Write(encryptedBytes, 0, length);
            }

            if (returnBuffer)
            {
                _pool.Return(buffer.Array);
            }

            _pool.Return(encryptedBytes);
            _pool.Return(tag);
            _pool.Return(nonce);

            encryptedStream.Seek(0, SeekOrigin.Begin);

            if (!leaveStreamOpen)
            {
                unencryptedStream.Close();
            }

            return(encryptedStream);
        }
示例#13
0
        public byte[] Decrypt(byte[] cipherText, byte[] key, byte[] nonce, byte[] tag, byte[] associatedData)
        {
            byte[] decryptedData = new byte[cipherText.Length];

            using (AesGcm aesGcm = new AesGcm(key))
            {
                aesGcm.Decrypt(nonce, cipherText, tag, decryptedData, associatedData);
            }

            return(decryptedData);
        }
示例#14
0
        public static byte[] AesGcmDecrypt(this byte[] input, byte[] key, byte[] nonce, byte[] tag)
        {
            byte[] decryptedText = new byte[input.Length];

            using (var aes = new AesGcm(key))
            {
                aes.Decrypt(nonce, input, tag, decryptedText);
            }

            return(decryptedText);
        }
        public static byte[] DecryptAesGcm(byte[] key, byte[] nonce, byte[] ciphertext, byte[] tag)
        {
            //複号後の値を格納する配列を準備
            byte[] plain = new byte[ciphertext.Length];

            using (var cipher = new AesGcm(key))
            {
                cipher.Decrypt(nonce, ciphertext, tag, plain);
            }
            return(plain);
        }
示例#16
0
	static string aesGcmEncryptToBase64(byte[] key, string data) {
    	byte[] plaintext = Encoding.UTF8.GetBytes(data);
    	byte[] gcmTag = new byte[16];
    	byte[] nonce = GenerateRandomNonce();
    	byte[] cipherText = new byte[plaintext.Length];
    	byte[] associatedData = new byte[0];
		using (var cipher = new AesGcm(key)) {
        	cipher.Encrypt(nonce, plaintext, cipherText, gcmTag, associatedData);
        	return Base64Encoding(nonce) + ":" + Base64Encoding(cipherText) + ":" + Base64Encoding(gcmTag);
    	}
	}
示例#17
0
        public static (byte[], byte[]) AesGcmEncrypt(this byte[] input, byte[] key, byte[] nonce)
        {
            byte[] tag           = new byte[16];
            byte[] encryptedText = new byte[input.Length];

            using (var aes = new AesGcm(key))
            {
                aes.Encrypt(nonce, input, encryptedText, tag);
            }

            return(encryptedText, tag);
        }
示例#18
0
        public AesGcmSymmetricCipher(byte[] key)
        {
            _aes = new AesGcm(key);
            var aes = new AesManaged();

            aes.Key     = key;
            aes.Mode    = CipherMode.CBC;
            aes.Padding = PaddingMode.Zeros;
            aes.IV      = new byte[16];
            _decryptor  = aes.CreateDecryptor();
            _encryptor  = aes.CreateEncryptor();
        }
示例#19
0
        public void Compliant()
        {
            GcmBlockCipher blockCipher = new GcmBlockCipher(new AesEngine()); // Compliant

            var aesGcm = new AesGcm(key);                                     // Compliant

            RSACryptoServiceProvider RSA1 = new RSACryptoServiceProvider();

            encryptedData = RSA1.Encrypt(data, true);                                               // Compliant
            RSA1.TryEncrypt(data, encryptedData, RSAEncryptionPadding.OaepSHA512, out byteWritten); // Compliant
            encryptedData = RSA1.Encrypt(data, RSAEncryptionPadding.OaepSHA1);                      // Compliant
        }
示例#20
0
        static string DecryptStringFromBytesAsync(byte[] ciphertext, string context, byte[] mac, byte[] key, byte[] iv)
        {
            var decrypted      = new byte[ciphertext.Length];
            var associatedData = Encoding.UTF8.GetBytes(context);

            using (var aes = new AesGcm(key))
            {
                aes.Decrypt(iv, ciphertext, mac, decrypted, associatedData);
            }

            return(Encoding.UTF8.GetString(decrypted));
        }
示例#21
0
	static string aesGcmDecryptFromBase64(byte[] key, string data) {
		string decryptedtext;
		byte[] associatedData = new byte[0];
		String[] parts = data.Split(':');
		byte[] ciphertext = Base64Decoding(parts[1]);
		byte[] decryptedData = new byte[ciphertext.Length];
		using (var cipher = new AesGcm(key)) {
        	cipher.Decrypt(Base64Decoding(parts[0]), ciphertext, Base64Decoding(parts[2]), decryptedData, associatedData);
			decryptedtext = Encoding.UTF8.GetString(decryptedData, 0, decryptedData.Length);
			return decryptedtext;
    	}
	}
示例#22
0
        public static void Decrypt(byte[] key
                                   , byte[] nonce, byte[] tag
                                   , byte[] ciphertext)
        {
            byte[] decryptedData = new byte[ciphertext.Length];
            using (AesGcm aes = new AesGcm(key))
                aes.Decrypt(nonce, ciphertext, tag, decryptedData);

            string decryptedText = Encoding.UTF8.GetString(decryptedData);

            Console.WriteLine(decryptedText);
        }
示例#23
0
        public byte[] Encrypt(byte[] toEncrypt, byte[] associatedData = null)
        {
            byte[] tag        = new byte[this.keySize];
            byte[] nonce      = new byte[this.nonceSize];
            byte[] cipherText = new byte[toEncrypt.Length];

            using (var cipher = new AesGcm(this._key))
            {
                cipher.Encrypt(nonce, toEncrypt, cipherText, tag, associatedData);
                return(Concat(tag, Concat(nonce, cipherText)));
            }
        }
 static void GCM_Encrypt(byte[] nonce, byte[] plaintext, byte[] ciphertext, byte[] tag, byte[] associatedData)
 {
     using (var gcm = new AesGcm(key))
     {
         gcm.Encrypt(
             nonce,
             plaintext,
             ciphertext,
             tag,
             associatedData);
     }
 }
示例#25
0
        protected void Cleanup()
        {
            AesGcm aes = null;

            while (_cipherPool.Count > 0)
            {
                while (!_cipherPool.TryPop(out aes))
                {
                }
                aes.Dispose();
            }
        }
示例#26
0
 public void GHash_returns_hash()
 {
     foreach (var i in TestCases)
     {
         var hash = AesGcm.GHash(i.HashKey,
                                 i.AuthData,
                                 i.AuthData.Length,
                                 i.Ciphertext,
                                 i.Ciphertext.Length);
         Assert.That(hash, Is.EqualTo(i.GHash));
     }
 }
示例#27
0
        public void Initialize(byte[] key)
        {
            if (IsInitialized)
            {
                throw new InvalidOperationException("PacketCrypt already initialized!");
            }

            _serverEncrypt = new AesGcm(key);
            _clientDecrypt = new AesGcm(key);

            IsInitialized = true;
        }
示例#28
0
    static string aesGcmDecrypt(byte[] key, byte[] nonce, byte[] ciphertext, byte[] gcmTag)
    {
        string decryptedtext;

        byte[] associatedData = new byte[0];
        byte[] decryptedData  = new byte[ciphertext.Length];
        using (var cipher = new AesGcm(key)) {
            cipher.Decrypt(nonce, ciphertext, gcmTag, decryptedData, associatedData);
            decryptedtext = Encoding.UTF8.GetString(decryptedData, 0, decryptedData.Length);
            return(decryptedtext);
        }
    }
示例#29
0
        public static void EncryptDecryptNullTag()
        {
            byte[] key        = "d5a194ed90cfe08abecd4691997ceb2c".HexToByteArray();
            byte[] nonce      = new byte[12];
            byte[] plaintext  = new byte[0];
            byte[] ciphertext = new byte[0];

            using (var aesGcm = new AesGcm(key))
            {
                Assert.Throws <ArgumentNullException>(() => aesGcm.Encrypt(nonce, plaintext, ciphertext, (byte[])null));
                Assert.Throws <ArgumentNullException>(() => aesGcm.Decrypt(nonce, ciphertext, (byte[])null, plaintext));
            }
        }
示例#30
0
文件: Helper.cs 项目: zhmkof/neo
        public static byte[] AES256Encrypt(this byte[] plainData, byte[] key, byte[] nonce, byte[] associatedData = null)
        {
            if (nonce.Length != 12)
            {
                throw new ArgumentOutOfRangeException(nameof(nonce));
            }
            var cipherBytes = new byte[plainData.Length];
            var tag         = new byte[16];

            using var cipher = new AesGcm(key);
            cipher.Encrypt(nonce, plainData, cipherBytes, tag, associatedData);
            return(Concat(nonce, cipherBytes, tag));
        }