Beispiel #1
0
        private byte[] DecryptWithKey(byte[] encryptedMessage, byte[] key, byte[] nonce)
        {
            try {
                int _macSize = 128;

                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))
                    {
                        var cipher     = new GcmBlockCipher(new AesEngine());
                        var parameters = new AeadParameters(new KeyParameter(key), _macSize, nonce);
                        cipher.Init(false, parameters);

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

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

                        return(plainText);
                        //return null;
                    }
            } catch (Exception e) {
                Debug.WriteLine(e.Message + e.Source + e.StackTrace + e.TargetSite);
                return(null);
            }
        }
Beispiel #2
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));
        }
Beispiel #3
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>
        /// Decrypts the message.
        /// </summary>
        /// <param name="encryptedMessage">The encrypted message.</param>
        /// <param name="key">The key.</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentException">
        /// key
        /// or
        /// Encrypted Message Required! - encryptedMessage
        /// </exception>
        /// <exception cref="System.Exception">Invalid version!</exception>
        public static string DecryptMessage(string encryptedMessage, string key)
        {
            byte[] encryptedMessageBytes = Convert.FromBase64String(encryptedMessage);
            byte[] keyBytes = Convert.FromBase64String(key);

            if (keyBytes == null || keyBytes.Length != KeyBitSize / 8)
            {
                throw new ArgumentException(string.Format("Key needs to be {0} bit!", KeyBitSize), "key");
            }

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

            using (var cipherStream = new MemoryStream(encryptedMessageBytes))
            {
                using (var cipherReader = new BinaryReader(cipherStream))
                {
                    // Get the Version
                    var version       = cipherReader.ReadBytes(1);
                    var versionString = Encoding.UTF8.GetString(version, 0, version.Length);
                    if (versionString != "1")
                    {
                        throw new Exception("Invalid version!");
                    }

                    // Get the tag
                    var tag = cipherReader.ReadBytes(TagBitSize / 8);

                    // Get the Nonce (IV)
                    var nonce = cipherReader.ReadBytes(NonceBitSize / 8);

                    var cipher     = new GcmBlockCipher(new AesEngine());
                    var parameters = new AeadParameters(new KeyParameter(keyBytes), TagBitSize, nonce);
                    cipher.Init(false, parameters);

                    //Decrypt Cipher Text
                    var cipherText = cipherReader.ReadBytes(encryptedMessage.Length - version.Length - nonce.Length);

                    byte[] cipherWithTag = new byte[cipherText.Length + tag.Length];
                    Array.Copy(cipherText, cipherWithTag, cipherText.Length);
                    Array.Copy(tag, 0, cipherWithTag, cipherText.Length, tag.Length);
                    var plainText = new byte[cipher.GetOutputSize(cipherWithTag.Length)];

                    try
                    {
                        var len = cipher.ProcessBytes(cipherWithTag, 0, cipherWithTag.Length, plainText, 0);
                        cipher.DoFinal(plainText, len);
                    }
                    catch (InvalidCipherTextException)
                    {
                        //Return null if it doesn't authenticate
                        return(null);
                    }

                    return(Encoding.UTF8.GetString(plainText, 0, plainText.Length));
                }
            }
        }
        //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());
            }
        }
        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);
            }
        }
Beispiel #7
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));
            }
        }
Beispiel #8
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));
            }
        }
Beispiel #9
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());
        }
    // 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);
    }
Beispiel #11
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);
        }
Beispiel #12
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;
        }
Beispiel #13
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));
        }
Beispiel #14
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);
        }
Beispiel #15
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);
        }
Beispiel #16
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);
        }
Beispiel #17
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));
                }
        }
Beispiel #18
0
        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));
        }
        /// <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));
        }
Beispiel #20
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);
        }
Beispiel #21
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());
        }
    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);
    }
Beispiel #23
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());
            }
        }
    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);
    }
Beispiel #25
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);
        }
Beispiel #26
0
        public static string encrypt(string PlainText, byte[] key, byte[] iv, long AAD, out byte[] outTag)
        {
            string sR = string.Empty;

            try
            {
                byte[] plainBytes = Encoding.ASCII.GetBytes(PlainText);

                GcmBlockCipher cipher     = new GcmBlockCipher(new AesFastEngine());
                AeadParameters parameters =
                    new AeadParameters(new KeyParameter(key), 128, iv, null);
                var tempAddBytesArr = BitConverter.GetBytes(AAD);
                cipher.Init(true, parameters);
                foreach (var item in tempAddBytesArr)
                {
                    cipher.ProcessAadByte(item);
                }
                byte[] encryptedBytes = new byte[cipher.GetOutputSize(plainBytes.Length)];
                Int32  retLen         = cipher.ProcessBytes
                                            (plainBytes, 0, plainBytes.Length, encryptedBytes, 0);
                outTag = cipher.GetMac();
                cipher.DoFinal(encryptedBytes, retLen);

                sR = Convert.ToBase64String(encryptedBytes, Base64FormattingOptions.None);
            }
            catch (Exception ex)
            {
                outTag = new byte[1] {
                    0x0
                };
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }
            return(sR);
        }
Beispiel #27
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);
        }
        //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);
                }
        }
Beispiel #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);
                }
        }
Beispiel #30
0
        private AesEncryptedData Encrypt(byte[] masterKey, byte[] iv, byte[] plainText)
        {
            var cipher     = new GcmBlockCipher(new AesEngine());
            var parameters = new AeadParameters(new KeyParameter(masterKey), AuthTagBitLength, iv);

            cipher.Init(true, parameters);

            var outputLength = cipher.GetOutputSize(plainText.Length);
            var output       = new byte[outputLength];

            // Produce cipher text
            var outputOffset = cipher.ProcessBytes(plainText, 0, plainText.Length, output, 0);

            // Produce authentication tag
            outputOffset += cipher.DoFinal(output, outputOffset);

            // Split output into cipher text and authentication tag
            var authTagLength = AuthTagBitLength / 8;

            var cipherText = new byte[outputOffset - authTagLength];
            var authTag    = new byte[authTagLength];

            Array.Copy(output, 0, cipherText, 0, cipherText.Length);
            Array.Copy(output, outputOffset - authTagLength, authTag, 0, authTag.Length);

            return(new AesEncryptedData()
            {
                EncryptedData = Convert.ToBase64String(cipherText),
                AuthTag = Convert.ToBase64String(authTag),
                Iv = Convert.ToBase64String(iv)
            });
        }