示例#1
0
        public string Encode(byte[] payload)
        {
            var nonceBytes = new byte[NonceBytes];

            _rng.GetBytes(nonceBytes);

            var headerBytes = new byte[HeaderBytes];

            Buffer.BlockCopy(_magicBytes, 0, headerBytes, 0, MagicBytes);
            Buffer.BlockCopy(nonceBytes, 0, headerBytes, MagicBytes, NonceBytes);

            var aead = new AeadParameters(_key, MacBytes * 8, nonceBytes, headerBytes);

            _gcmEngine.Init(true, aead);

            var cipherTextBytes = new byte[_gcmEngine.GetOutputSize(payload.Length)];

            var pos = _gcmEngine.ProcessBytes(payload, 0, payload.Length, cipherTextBytes, 0);

            _gcmEngine.DoFinal(cipherTextBytes, pos);

            var result = new byte[HeaderBytes + cipherTextBytes.Length];

            Buffer.BlockCopy(headerBytes, 0, result, 0, HeaderBytes);
            Buffer.BlockCopy(cipherTextBytes, 0, result, HeaderBytes, cipherTextBytes.Length);

            return(ToCompatBase64Url(result));
        }
示例#2
0
        private static void TestBC(byte[] key, byte[] iv, byte[] aad, byte[] ciphertext, byte[] tag, byte[] plaintext)
        {
            try
            {
                var cipher = new GcmBlockCipher(new AesEngine());
                var parms  = new AeadParameters(new KeyParameter(key), tag.Length * 8, iv, aad);
                cipher.Init(false, parms);

                byte[] output = new byte[cipher.GetOutputSize(ciphertext.Length + tag.Length)];
                int    off    = cipher.ProcessBytes(ciphertext, 0, ciphertext.Length, output, 0);
                off += cipher.ProcessBytes(tag, 0, tag.Length, output, off);
                cipher.DoFinal(output, off);

                if (plaintext != null && plaintext.SequenceEqual(output))
                {
                    testsPassedBC++;
                }
                else
                {
                    testsFailedBC++;
                }
            }
            catch (Exception ex)
            {
                if (plaintext == null)
                {
                    testsPassedBC++;
                }
                else
                {
                    testsFailedBC++;
                }
            }
        }
示例#3
0
        private void AES_GCM_Decrypt(byte[] k)
        {
            GcmBlockCipher cipher = new GcmBlockCipher(new AesEngine(), new BasicGcmMultiplier());
            KeyParameter   contentKey;

            //  The requirements from JWA
            //  IV is 96 bits
            //  Authentication tag is 128 bits
            //  key sizes are 128, 192 and 256 bits

            contentKey = new KeyParameter(k);

            byte[] a = CreateAad();

            AeadParameters parameters = new AeadParameters(contentKey, 128, _iv, a);

            cipher.Init(false, parameters);
            byte[] c   = new byte[cipher.GetOutputSize(_RgbEncrypted.Length + _Tag.Length)];
            int    len = cipher.ProcessBytes(_RgbEncrypted, 0, _RgbEncrypted.Length, c, 0);

            len += cipher.ProcessBytes(_Tag, 0, _Tag.Length, c, len);
            cipher.DoFinal(c, len);

            payload = c;
        }
示例#4
0
        private byte[] AESGCM_KeyWrap(byte[] key, EncryptMessage msg)
        {
            GcmBlockCipher cipher = new GcmBlockCipher(new AesEngine(), new BasicGcmMultiplier());
            KeyParameter   contentKey;

            //  The requirements from JWA
            //  IV is 96 bits
            //  Authentication tag is 128 bits
            //  key sizes are 128, 192 and 256 bits
            //  Keywrap says that there is no AAD

            contentKey = new KeyParameter(key);
            byte[] a   = new byte[0];
            byte[] iv  = Message.base64urldecode(FindAttr("iv", msg).AsString());
            byte[] tag = Message.base64urldecode(FindAttr("tag", msg).AsString());

            AeadParameters parameters = new AeadParameters(contentKey, 128, iv, a);

            cipher.Init(false, parameters);
            byte[] c   = new byte[cipher.GetOutputSize(_rgbEncrypted.Length + tag.Length)];
            int    len = cipher.ProcessBytes(_rgbEncrypted, 0, _rgbEncrypted.Length, c, 0);

            len += cipher.ProcessBytes(tag, 0, tag.Length, c, len);
            cipher.DoFinal(c, len);

            return(c);
        }
示例#5
0
        private static byte[] bouncyCastleCrypto(bool forEncrypt, byte[] input, string key, Encoding enc)
        {
            string key2 = getUsingKey(key);

            try
            {
                byte[] keyByte = enc.GetBytes(key2);
                byte[] nonce   = new byte[NONCE_BIT_SIZE / 8];
                if (forEncrypt)
                {
                    SecureRandom random = new SecureRandom();
                    random.NextBytes(nonce, 0, nonce.Length);
                    AeadParameters parameters = new AeadParameters(new KeyParameter(keyByte), MAC_BIT_SIZE, nonce);
                    _cipher.Init(forEncrypt, parameters);
                    byte[] output_bytes = new byte[_cipher.GetOutputSize(input.Length)];
                    int    len          = _cipher.ProcessBytes(input, 0, input.Length, output_bytes, 0);
                    _cipher.DoFinal(output_bytes, len);
                    using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
                    {
                        using (System.IO.BinaryWriter binaryWriter = new System.IO.BinaryWriter(ms))
                        {
                            binaryWriter.Write(nonce);
                            binaryWriter.Write(output_bytes);
                        }
                        return(ms.ToArray());
                    }
                }
                else
                {
                    using (System.IO.MemoryStream ms = new System.IO.MemoryStream(input))
                    {
                        using (System.IO.BinaryReader reader = new System.IO.BinaryReader(ms))
                        {
                            nonce = reader.ReadBytes(NONCE_BIT_SIZE / 8);
                            AeadParameters parameters = new AeadParameters(new KeyParameter(keyByte), MAC_BIT_SIZE, nonce);
                            _cipher.Init(forEncrypt, parameters);
                            byte[] cipherBytes = reader.ReadBytes(input.Length - nonce.Length);
                            byte[] plain_bytes = new byte[_cipher.GetOutputSize(cipherBytes.Length)];
                            int    len         = _cipher.ProcessBytes(cipherBytes, 0, cipherBytes.Length, plain_bytes, 0);
                            _cipher.DoFinal(plain_bytes, len);
                            return(plain_bytes);
                        }
                    }
                }

                //_cipher.Init(forEncrypt, new KeyParameter(keyByte));
                //return _cipher.DoFinal(input);
            }
            catch (Org.BouncyCastle.Crypto.CryptoException ex)
            {
                throw new InvalidOperationException(ex.Message);
            }
        }
        /// <summary>
        /// Encrypt the specified data using the specified salt.
        ///Encrypt uses provided salt, uses master key
        ///& salt to generate per-data key & nonce with the help of HKDF
        ///Salt is concatenated to the ciphertext
        /// </summary>
        /// <returns>The encrypted data bytes.</returns>
        /// <param name="data">Data to be encrypted.</param>
        public byte[] EncryptWithSalt(byte[] data, byte[] salt)
        {
            Validation.NotNull(data);
            Validation.NotNullOrEmptyByteArray(salt);

            var hkdf = new HkdfBytesGenerator(new Sha512Digest());

            hkdf.Init(new HkdfParameters(this.key, salt, this.domain));

            var keyNonce = new byte[SymKeyLen + SymNonceLen];

            hkdf.GenerateBytes(keyNonce, 0, keyNonce.Length);

            var cipher         = new GcmBlockCipher(new AesEngine());
            var keyNonceSlice1 = ((Span <byte>)keyNonce).Slice(0, SymKeyLen);
            var keyNonceSlice2 = ((Span <byte>)keyNonce).Slice(SymKeyLen);

            var parameters = new AeadParameters(
                new KeyParameter(keyNonceSlice1.ToArray()),
                SymTagLen * 8,
                keyNonceSlice2.ToArray());

            cipher.Init(true, parameters);

            var cipherText = new byte[cipher.GetOutputSize(data.Length)];
            var len        = cipher.ProcessBytes(data, 0, data.Length, cipherText, 0);

            cipher.DoFinal(cipherText, len);

            return(Bytes.Combine(salt, cipherText));
        }
示例#7
0
        public static byte[] Decrypt(string key, byte[] encrypted)
        {
            byte[] unencrypted;
            byte[] nonce = GetIv(key);
            // Create the streams used for encryption.
            GcmBlockCipher objCipher = new GcmBlockCipher(new AesEngine());

            objCipher.Init(true, new AeadParameters(new KeyParameter(GetKey(key)), 128, nonce, null));

            //Decrypt Cipher Text
            using (MemoryStream objStream = new MemoryStream(encrypted))
                using (BinaryReader objReader = new BinaryReader(objStream))
                {
                    byte[] cipherText = objReader.ReadBytes(encrypted.Length);
                    unencrypted = new byte[objCipher.GetOutputSize(cipherText.Length)];

                    try
                    {
                        int len = objCipher.ProcessBytes(cipherText, 0, cipherText.Length, unencrypted, 0);
                        objCipher.DoFinal(unencrypted, len);
                    }
                    catch (InvalidCipherTextException)
                    {
                        //Return null if it doesn't authenticate
                        return(Array.Empty <byte>());
                    }
                }

            return(unencrypted);
        }
        //encrypt with byte array
        private byte[] EncryptWithKey(byte[] text, byte[] key, byte[] nonSecretPayload = null)
        {
            if (key == null || key.Length != KEY_BIT_SIZE / 8)
            {
                throw new ArgumentException(String.Format("Key needs to be {0} bit!", KEY_BIT_SIZE), "key");
            }

            nonSecretPayload = nonSecretPayload ?? new byte[] { };
            var nonce = new byte[NONCE_BIT_SIZE / 8];

            _random.NextBytes(nonce, 0, nonce.Length);
            var cipher     = new GcmBlockCipher(new AesEngine());
            var parameters = new AeadParameters(new KeyParameter(key), MAC_BIT_SIZE, nonce, nonSecretPayload);

            cipher.Init(true, parameters);
            var cipherData = new byte[cipher.GetOutputSize(text.Length)];
            var len        = cipher.ProcessBytes(text, 0, text.Length, cipherData, 0);

            cipher.DoFinal(cipherData, len);
            using (var combinedStream = new MemoryStream())
            {
                using (var binaryWriter = new BinaryWriter(combinedStream))
                {
                    binaryWriter.Write(nonSecretPayload);
                    binaryWriter.Write(nonce);
                    binaryWriter.Write(cipherData);
                }
                return(combinedStream.ToArray());
            }
        }
示例#9
0
        public string decrypt_data(byte[] data)
        {
            var encryptedData = data;
            var encKey        = File.ReadAllText(Environment.GetEnvironmentVariable("APPDATA").GoUpNLevels() + @"/Local/Google/Chrome/User Data/Local State");

            encKey = JObject.Parse(encKey)["os_crypt"]["encrypted_key"].ToString();
            var decodedKey = ProtectedData.Unprotect(Convert.FromBase64String(encKey).Skip(5).ToArray(), null, DataProtectionScope.LocalMachine);

            const int MAC_BIT_SIZE   = 128;
            const int NONCE_BIT_SIZE = 96;

            using (var cipherStream = new MemoryStream(encryptedData))
                using (var cipherReader = new BinaryReader(cipherStream))
                {
                    var nonSecretPayload = cipherReader.ReadBytes(3);
                    var nonce            = cipherReader.ReadBytes(NONCE_BIT_SIZE / 8);
                    var cipher           = new GcmBlockCipher(new AesEngine());
                    var parameters       = new AeadParameters(new KeyParameter(decodedKey), MAC_BIT_SIZE, nonce);
                    cipher.Init(false, parameters);
                    var cipherText = cipherReader.ReadBytes(encryptedData.Length);
                    var plainText  = new byte[cipher.GetOutputSize(cipherText.Length)];
                    try
                    {
                        var len = cipher.ProcessBytes(cipherText, 0, cipherText.Length, plainText, 0);
                        cipher.DoFinal(plainText, len);
                    }
                    catch (InvalidCipherTextException)
                    {
                    }

                    return(Encoding.Default.GetString(plainText));
                }
        }
示例#10
0
        public MemoryStream Encrypt(MemoryStream data)
        {
            byte[]         nonce      = generateRandomBytes(SALT_LENGTH);
            GcmBlockCipher cipher     = new GcmBlockCipher(new AesEngine());
            AeadParameters parameters = new AeadParameters(new KeyParameter(this.key), TAG_LENGTH * 8, nonce, null);

            cipher.Init(true, parameters);

            var plaintext = data.ToArray();

            byte[] ciphertext = new byte[cipher.GetOutputSize(plaintext.Length)];
            int    len        = cipher.ProcessBytes(plaintext, 0, plaintext.Length, ciphertext, 0);

            cipher.DoFinal(ciphertext, len);

            // Assemble message
            var combinedStream = new MemoryStream();
            var binaryWriter   = new BinaryWriter(combinedStream);

            // Prepend Nonce
            binaryWriter.Write(nonce);

            // Write Cipher Text
            binaryWriter.Write(ciphertext);

            return(combinedStream);
        }
        private void DoTestExceptions()
        {
            GcmBlockCipher gcm = new GcmBlockCipher(CreateAesEngine());

            try
            {
                gcm = new GcmBlockCipher(new DesEngine());

                Fail("incorrect block size not picked up");
            }
            catch (ArgumentException)
            {
                // expected
            }

            try
            {
                gcm.Init(false, new KeyParameter(new byte[16]));

                Fail("illegal argument not picked up");
            }
            catch (ArgumentException)
            {
                // expected
            }

            AeadTestUtilities.TestTampering(this, gcm, new AeadParameters(new KeyParameter(new byte[16]), 128, new byte[16]));

            byte[] P   = Strings.ToByteArray("Hello world!");
            byte[] buf = new byte[100];

            GcmBlockCipher c = new GcmBlockCipher(CreateAesEngine());
            AeadParameters aeadParameters = new AeadParameters(new KeyParameter(new byte[16]), 128, new byte[16]);

            c.Init(true, aeadParameters);

            c.ProcessBytes(P, 0, P.Length, buf, 0);

            c.DoFinal(buf, 0);

            try
            {
                c.DoFinal(buf, 0);
                Fail("no exception on reuse");
            }
            catch (InvalidOperationException e)
            {
                IsTrue("wrong message", e.Message.Equals("GCM cipher cannot be reused for encryption"));
            }

            try
            {
                c.Init(true, aeadParameters);
                Fail("no exception on reuse");
            }
            catch (ArgumentException e)
            {
                IsTrue("wrong message", e.Message.Equals("cannot reuse nonce for GCM encryption"));
            }
        }
示例#12
0
        /// <summary>
        /// Encryption And Authentication (AES-GCM) of a UTF8 string.
        /// </summary>
        /// <param name="strToken">Token to Encrypt.</param>
        /// <param name="key">The key.</param>
        /// <returns>Encrypted Message</returns>
        /// <remarks>
        /// Adds overhead of (Optional-Payload + BlockSize(16) + Message +  HMac-Tag(16)) * 1.33 Base64
        /// </remarks>
        public static byte[] AESGCMEncrypt(byte[] strToken, byte[] key, bool blnVerbose)
        {
            //User Error Checks
            if (key == null || key.Length != KeyBitSize / 8)
            {
                throw new ArgumentException(String.Format("Key needs to be {0} bit!", KeyBitSize), "key");
            }

            //Using random nonce large enough not to repeat
            byte[] iv = new byte[NonceBitSize / 8];
            Random.NextBytes(iv, 0, iv.Length);
            var cipher = new GcmBlockCipher(new AesFastEngine());
            // var parameters = new AeadParameters(new KeyParameter(key), MacBitSize, nonce, nonSecretPayload);
            KeyParameter      keyParam   = new KeyParameter(key);
            ICipherParameters parameters = new ParametersWithIV(keyParam, iv);

            cipher.Init(true, parameters);
            //Generate Cipher Text With Auth Tag
            var cipherText = new byte[cipher.GetOutputSize(strToken.Length)];
            var len        = cipher.ProcessBytes(strToken, 0, strToken.Length, cipherText, 0);
            int len2       = cipher.DoFinal(cipherText, len);

            //Assemble Message
            using (var combinedStream = new MemoryStream())
            {
                using (var binaryWriter = new BinaryWriter(combinedStream))
                {
                    //Prepend Nonce
                    binaryWriter.Write(iv);
                    //Write Cipher Text
                    binaryWriter.Write(cipherText);
                }
                return(combinedStream.ToArray());
            }
        }
示例#13
0
        public static byte[] Aes256Decrypt(ReadOnlyMemory <byte> encryptedData, ReadOnlyMemory <byte> key, EncryptionOptions options = null)
        {
            if (key.Length != Constants.Aes256.KeySize || encryptedData.Length == 0)
            {
                return(null);
            }

            using var cipherStream = new MemoryStream(encryptedData.ToArray());
            using var cipherReader = new BinaryReader(cipherStream);

            var nonce = cipherReader.ReadBytes(options?.NonceSize ?? Constants.Aes256.NonceSize);

            var cipher     = new GcmBlockCipher(new AesEngine());
            var parameters = new AeadParameters(new KeyParameter(key.ToArray()), options?.MacBitSize ?? Constants.Aes256.MacBitSize, nonce);

            cipher.Init(false, parameters);

            var cipherText = cipherReader.ReadBytes(encryptedData.Length - nonce.Length);
            var plainText  = new byte[cipher.GetOutputSize(cipherText.Length)];

            try
            { cipher.DoFinal(plainText, cipher.ProcessBytes(cipherText, 0, cipherText.Length, plainText, 0)); }
            catch (InvalidCipherTextException)
            { return(null); }

            return(plainText);
        }
示例#14
0
文件: Helper.cs 项目: neo-project/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 tag         = new byte[16];
            var cipherBytes = new byte[plainData.Length];

            if (!IsOSX)
            {
                using var cipher = new AesGcm(key);
                cipher.Encrypt(nonce, plainData, cipherBytes, tag, associatedData);
            }
            else
            {
                var cipher     = new GcmBlockCipher(new AesEngine());
                var parameters = new AeadParameters(
                    new KeyParameter(key),
                    128, //128 = 16 * 8 => (tag size * 8)
                    nonce,
                    associatedData);
                cipher.Init(true, parameters);
                cipherBytes = new byte[cipher.GetOutputSize(plainData.Length)];
                var length = cipher.ProcessBytes(plainData, 0, plainData.Length, cipherBytes, 0);
                cipher.DoFinal(cipherBytes, length);
            }
            return(Concat(nonce, cipherBytes, tag));
        }
示例#15
0
        public byte[] Encrypt(byte[] message, byte[] nonSecret = null)
        {
            var nonce = new byte[NonceBitSize / 8];

            _secureRandom.NextBytes(nonce, 0, nonce.Length);

            nonSecret = nonSecret ?? new byte[] { };

            var cipher     = new GcmBlockCipher(new AesEngine());
            var parameters = new AeadParameters(
                new KeyParameter(_key), MacBitSize, nonce, nonSecret
                );

            cipher.Init(true, parameters);

            var cipherText = new byte[cipher.GetOutputSize(message.Length)];
            int len        =
                cipher.ProcessBytes(message, 0, message.Length, cipherText, 0);

            cipher.DoFinal(cipherText, len);

            using var combinedStream = new MemoryStream();
            using (var binaryWriter = new BinaryWriter(combinedStream))
            {
                binaryWriter.Write(nonSecret);
                binaryWriter.Write(nonce);
                binaryWriter.Write(cipherText);
            }

            return(combinedStream.ToArray());
        }
    // Token: 0x06000013 RID: 19 RVA: 0x00003260 File Offset: 0x00001460
    private static string smethod_15(byte[] byte_0, byte[] byte_1, int int_1)
    {
        string @string;

        using (MemoryStream memoryStream = new MemoryStream(byte_0))
        {
            using (BinaryReader binaryReader = new BinaryReader(memoryStream))
            {
                binaryReader.ReadBytes(int_1);
                byte[]         array          = binaryReader.ReadBytes(12);
                GcmBlockCipher gcmBlockCipher = new GcmBlockCipher(new AesEngine());
                AeadParameters aeadParameters = new AeadParameters(new KeyParameter(byte_1), 128, array);
                gcmBlockCipher.Init(false, aeadParameters);
                byte[] array2 = binaryReader.ReadBytes(byte_0.Length);
                byte[] array3 = new byte[gcmBlockCipher.GetOutputSize(array2.Length)];
                try
                {
                    int num = gcmBlockCipher.ProcessBytes(array2, 0, array2.Length, array3, 0);
                    gcmBlockCipher.DoFinal(array3, num);
                }
                catch
                {
                    return(null);
                }
                @string = Encoding.Default.GetString(array3);
            }
        }
        return(@string);
    }
示例#17
0
        /// <summary>
        /// 敏感信息加密需要从https://api.mch.weixin.qq.com/risk/getcertficates此接口下载加密证书进行下一步加密,
        /// 该接口下载到的是密文,使用此AESGCM.Decrypt()方法解密得到证书明文
        /// </summary>
        /// <param name="ciphertext">接口下载得到的JSON里的ciphertext字段</param>
        /// <param name="key">微信支付商户后台设置的V3密钥</param>
        /// <param name="ivs">接口下载得到的JSON里的nonce字段</param>
        /// <param name="associatedText">默认为certificate,不需更改</param>
        /// <returns> 返回公钥明文,-----BEGIN CERTIFICATE----- </returns>
        public static string Decrypt(string ciphertext, string key, string ivs, string associatedText = "certificate")
        {
            var buff           = Convert.FromBase64String(ciphertext);
            var secret         = Encoding.UTF8.GetBytes(key);
            var nonce          = Encoding.UTF8.GetBytes(ivs);
            var associatedData = Encoding.UTF8.GetBytes(associatedText);

            // 算法 AEAD_AES_256_GCM,C# 环境使用 BouncyCastle.Crypto.dll 类库实现
            var cipher = new GcmBlockCipher(new AesFastEngine());
            var aead   = new AeadParameters(new KeyParameter(secret), 128, nonce, associatedData);

            cipher.Init(false, aead);

            var data = new byte[cipher.GetOutputSize(buff.Length)];
            var num  = cipher.ProcessBytes(buff, 0, buff.Length, data, 0);

            try
            {
                cipher.DoFinal(data, num);
            }
            catch (Exception)
            {
            }

            return(Encoding.UTF8.GetString(data));
        }
示例#18
0
        public static byte[] AES_GCMEncrypt(byte[] cleartext, byte[] keyBytes)
        {
            // Create a random nonce byte array
            SecureRandom rng = new SecureRandom();

            byte[] nonce = new byte[NONCE_SIZE];
            rng.NextBytes(nonce);

            // Specify AES-GCM block cipher
            var blockCipher  = new GcmBlockCipher(new AesEngine());
            var keyParam     = ParameterUtilities.CreateKeyParameter(ENCRYPTION_METHOD, keyBytes); // Use 256 bit key for AES-256
            var cipherParams = new ParametersWithIV(keyParam, nonce);

            blockCipher.Init(true, cipherParams);

            // Encrypts ciphertext
            byte[] ciphertext = new byte[blockCipher.GetOutputSize(cleartext.Length)];
            int    length     = blockCipher.ProcessBytes(cleartext, 0, cleartext.Length, ciphertext, 0);

            blockCipher.DoFinal(ciphertext, length);

            // Prepends the nonce to the ciphertext (in front)
            byte[] ciphertextWithNonce = new byte[nonce.Length + ciphertext.Length];
            Array.Copy(nonce, 0, ciphertextWithNonce, 0, nonce.Length);
            Array.Copy(ciphertext, 0, ciphertextWithNonce, nonce.Length, ciphertext.Length);

            return(ciphertextWithNonce);
        }
示例#19
0
        private void AES_GCM_Encrypt(byte[] k)
        {
            GcmBlockCipher cipher = new GcmBlockCipher(new AesEngine(), new BasicGcmMultiplier());
            KeyParameter   contentKey;

            //  The requirements from JWA
            //  IV is 96 bits
            //  Authentication tag is 128 bits
            //  key sizes are 128, 192 and 256 bits

            _iv = new byte[96 / 8];
            s_PRNG.NextBytes(_iv);

            contentKey = new KeyParameter(k);

            //  Build the object to be hashed

            byte[]         a          = CreateAad();
            AeadParameters parameters = new AeadParameters(contentKey, 128, _iv, a);

            cipher.Init(true, parameters);

            byte[] c   = new byte[cipher.GetOutputSize(payload.Length)];
            int    len = cipher.ProcessBytes(payload, 0, payload.Length, c, 0);

            cipher.DoFinal(c, len);

            _RgbEncrypted = c;
            _Tag          = cipher.GetMac();
            Array.Resize(ref _RgbEncrypted, _RgbEncrypted.Length - _Tag.Length);
        }
        private static byte[] EncryptAesGcmWithBouncyCastle(byte[] plaintext, byte[] key, byte[] nonce, out byte[] tag)
        {
            const int tagLenth = 16; // in bytes

            var plaintextBytes = plaintext;
            var bcCiphertext   = new byte[plaintextBytes.Length + tagLenth];

            var cipher     = new GcmBlockCipher(new AesEngine());
            var parameters = new AeadParameters(new KeyParameter(key), tagLenth * 8, nonce);

            cipher.Init(true, parameters);

            var offset = cipher.ProcessBytes(plaintextBytes, 0, plaintextBytes.Length, bcCiphertext, 0);

            cipher.DoFinal(bcCiphertext, offset);

            // Bouncy Castle includes the authentication tag in the ciphertext
            var ciphertext = new byte[plaintextBytes.Length];

            tag = new byte[tagLenth];
            Buffer.BlockCopy(bcCiphertext, 0, ciphertext, 0, plaintextBytes.Length);
            Buffer.BlockCopy(bcCiphertext, plaintextBytes.Length, tag, 0, tagLenth);

            return(ciphertext);
        }
示例#21
0
        public static string EncryptSymmetric <T>(this T data, string symmetricKey, string initialisationVector)
        {
            var       keyParameter = new KeyParameter(Convert.FromBase64String(symmetricKey));
            const int macSize      = 128;
            var       nonce        = new byte[128 / 8];

            nonce = Encoding.UTF8.GetBytes(initialisationVector).Take(nonce.Length).ToArray();
            var associatedText = new byte[] { };
            var cipher         = new GcmBlockCipher(new AesFastEngine());
            var parameters     = new AeadParameters(keyParameter, macSize, nonce, associatedText);

            cipher.Init(true, parameters);
            using (MemoryStream ms = new MemoryStream())
            {
                Serializer.Serialize <T>(ms, data);
                ms.Position = 0;
                byte[] msg;
                using (BinaryReader br = new BinaryReader(ms))
                    msg = br.ReadBytes((int)ms.Length);
                var encdata = new byte[cipher.GetOutputSize(msg.Length)];
                var len     = cipher.ProcessBytes(msg, 0, msg.Length, encdata, 0);
                cipher.DoFinal(encdata, len);
                return(Convert.ToBase64String(encdata));
            }
        }
    public static string Decrypt(string EncryptedText)
    {
        string sR = string.Empty;

        try
        {
            byte[] key = HexToByte("2143B39425BBD08B6E8E61C5D1E1BC9F428FC569FBC6F78C0BC48FCCDB0F89AE");
            byte[] iv  = HexToByte("E1E592E89225847C19D948684F3B070D");

            byte[] encryptedBytes = Convert.FromBase64String(EncryptedText);

            GcmBlockCipher cipher     = new GcmBlockCipher(new AesFastEngine());
            AeadParameters parameters =
                new AeadParameters(new KeyParameter(key), 128, iv, null);
            //ParametersWithIV parameters = new ParametersWithIV(new KeyParameter(key), iv);

            cipher.Init(false, parameters);
            byte[] plainBytes = new byte[cipher.GetOutputSize(encryptedBytes.Length)];
            Int32  retLen     = cipher.ProcessBytes
                                    (encryptedBytes, 0, encryptedBytes.Length, plainBytes, 0);
            cipher.DoFinal(plainBytes, retLen);

            sR = Encoding.UTF8.GetString(plainBytes).TrimEnd("\r\n\0".ToCharArray());
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }

        return(sR);
    }
示例#23
0
        public static byte[] Aes256Encrypt(ReadOnlyMemory <byte> data, ReadOnlyMemory <byte> key, EncryptionOptions options = null)
        {
            if (key.Length != Constants.Aes256.KeySize || data.Length == 0)
            {
                return(null);
            }

            var nonce = new byte[options?.NonceSize ?? Constants.Aes256.NonceSize];

            Random.NextBytes(nonce);

            var cipher = new GcmBlockCipher(new AesEngine());

            cipher.Init(true, new AeadParameters(new KeyParameter(key.ToArray()), options?.MacBitSize ?? Constants.Aes256.MacBitSize, nonce));

            var cipherText = new byte[cipher.GetOutputSize(data.Length)];

            cipher.DoFinal(cipherText, cipher.ProcessBytes(data.ToArray(), 0, data.Length, cipherText, 0));

            using var cs = new MemoryStream();
            using (var bw = new BinaryWriter(cs))
            {
                bw.Write(nonce);
                bw.Write(cipherText);
            }

            return(cs.ToArray());
        }
    public static string Encrypt(string PlainText)
    {
        string sR = string.Empty;

        try
        {
            byte[] key = HexToByte("2143B39425BBD08B6E8E61C5D1E1BC9F428FC569FBC6F78C0BC48FCCDB0F89AE");
            byte[] iv  = HexToByte("E1E592E89225847C19D948684F3B070D");

            byte[] plainBytes = Encoding.UTF8.GetBytes(PlainText);

            GcmBlockCipher cipher     = new GcmBlockCipher(new AesFastEngine());
            AeadParameters parameters =
                new AeadParameters(new KeyParameter(key), 128, iv, null);

            cipher.Init(true, parameters);

            byte[] encryptedBytes = new byte[cipher.GetOutputSize(plainBytes.Length)];
            Int32  retLen         = cipher.ProcessBytes
                                        (plainBytes, 0, plainBytes.Length, encryptedBytes, 0);
            cipher.DoFinal(encryptedBytes, retLen);
            sR = Convert.ToBase64String(encryptedBytes, Base64FormattingOptions.None);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }

        return(sR);
    }
        public byte[] EncryptName(byte[] input, int paddedLength)
        {
            try
            {
                byte[] inputPadded = new byte[paddedLength];

                if (input.Length > inputPadded.Length)
                {
                    throw new ArgumentException($"Input is too long: {Encoding.UTF8.GetString(input)}");
                }

                Array.Copy(input, 0, inputPadded, 0, input.Length);

                byte[] nonce = Util.GetSecretBytes(12);

                GcmBlockCipher cipher = new GcmBlockCipher(new AesEngine());
                cipher.Init(true, new AeadParameters(new KeyParameter(key), 128, nonce));

                byte[] ciphertext = new byte[cipher.GetUpdateOutputSize(inputPadded.Length)];
                cipher.ProcessBytes(inputPadded, 0, inputPadded.Length, ciphertext, 0);

                byte[] tag = new byte[cipher.GetOutputSize(0)];
                cipher.DoFinal(tag, 0);

                return(ByteUtil.combine(nonce, ciphertext, tag));
            }
            catch (InvalidCipherTextException ex)
            {
                throw new ArgumentException(null, ex);
            }
        }
        public override void Write(byte[] buffer, int offset, int count)
        {
            byte[] output    = new byte[cipher.GetUpdateOutputSize(count)];
            int    encrypted = cipher.ProcessBytes(buffer, offset, count, output, 0);

            base.Write(output, 0, encrypted);
        }
示例#27
0
        public MemoryStream Decrypt(MemoryStream data)
        {
            if (data.Length > int.MaxValue)
            {
                throw new ArgumentException("Data to decrypt should be smaller than 2GB");
            }

            using (var cipherReader = new BinaryReader(data))
            {
                data.Position = 0;
                var nonce = cipherReader.ReadBytes(SALT_LENGTH);

                var cipher     = new GcmBlockCipher(new AesEngine());
                var parameters = new AeadParameters(new KeyParameter(this.key), TAG_LENGTH * 8, nonce, null);
                cipher.Init(false, parameters);

                int dataLength = (int)data.Length - SALT_LENGTH;
                var ciphertext = cipherReader.ReadBytes(dataLength);
                var plaintext  = new byte[cipher.GetOutputSize(ciphertext.Length)];

                var len = cipher.ProcessBytes(ciphertext, 0, ciphertext.Length, plaintext, 0);

                cipher.DoFinal(plaintext, len);

                return(new MemoryStream(plaintext));
            }
        }
示例#28
0
        public string Decode(byte[] data, byte[] nonce, int macBits)
        {
            string sR = "";

            try
            {
                GcmBlockCipher cipher = new GcmBlockCipher(new AesEngine());

                AeadParameters parameters = new AeadParameters(new KeyParameter(key), macBits, nonce);

                cipher.Init(false, parameters);
                byte[] plainBytes = new byte[cipher.GetOutputSize(data.Length)];
                int    retLen     = cipher.ProcessBytes(data, 0, data.Length, plainBytes, 0);
                cipher.DoFinal(plainBytes, retLen);

                sR = System.Text.Encoding.UTF8.GetString(plainBytes).TrimEnd("\r\n\0".ToCharArray());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }

            return(sR);
        }
示例#29
0
        private byte[] DecryptWithKey(byte[] encryptedMessage, byte[] key, int nonSecretPayloadLength = 0)
        {
            //User Error Checks
            CheckKey(key);

            if (encryptedMessage == null || encryptedMessage.Length == 0)
            {
                throw new ArgumentException("Encrypted Message Required!", "encryptedMessage");
            }

            using (var cipherStream = new MemoryStream(encryptedMessage))
                using (var cipherReader = new BinaryReader(cipherStream))
                {
                    //Grab Payload
                    var nonSecretPayload = cipherReader.ReadBytes(nonSecretPayloadLength);

                    //Grab Nonce
                    var nonce = cipherReader.ReadBytes(_nonceSize / 8);

                    var cipher     = new GcmBlockCipher(new AesEngine());
                    var parameters = new AeadParameters(new KeyParameter(key), _macSize, nonce, nonSecretPayload);
                    cipher.Init(false, parameters);

                    //Decrypt Cipher Text
                    var cipherText = cipherReader.ReadBytes(encryptedMessage.Length - nonSecretPayloadLength - nonce.Length);
                    var plainText  = new byte[cipher.GetOutputSize(cipherText.Length)];

                    var len = cipher.ProcessBytes(cipherText, 0, cipherText.Length, plainText, 0);
                    cipher.DoFinal(plainText, len);

                    return(plainText);
                }
        }
        //decrypt with byte array
        private byte[] DecryptWithKey(byte[] message, byte[] key, int nonSecretPayloadLength = 0)
        {
            if (key == null || key.Length != KEY_BIT_SIZE / 8)
            {
                throw new ArgumentException(String.Format("Key needs to be {0} bit!", KEY_BIT_SIZE), "key");
            }
            if (message == null || message.Length == 0)
            {
                throw new ArgumentException("Message required!", "message");
            }

            using (var cipherStream = new MemoryStream(message))
                using (var cipherReader = new BinaryReader(cipherStream))
                {
                    var nonSecretPayload = cipherReader.ReadBytes(nonSecretPayloadLength);
                    var nonce            = cipherReader.ReadBytes(NONCE_BIT_SIZE / 8);
                    var cipher           = new GcmBlockCipher(new AesEngine());
                    var parameters       = new AeadParameters(new KeyParameter(key), MAC_BIT_SIZE, nonce, nonSecretPayload);
                    cipher.Init(false, parameters);
                    var cipherData = cipherReader.ReadBytes(message.Length - nonSecretPayloadLength - nonce.Length);
                    var plainText  = new byte[cipher.GetOutputSize(cipherData.Length)];
                    try
                    {
                        var len = cipher.ProcessBytes(cipherData, 0, cipherData.Length, plainText, 0);
                        cipher.DoFinal(plainText, len);
                    }
                    catch (InvalidCipherTextException)
                    {
                        return(null);
                    }
                    return(plainText);
                }
        }