mervick / aes-everywhere

Aes Everywhere - Cross Language AES 256 Encryption Library (Bash, Powershell, C#, Dart, GoLang, Java, JavaScript, Lua, PHP, Python, Ruby, Swift)
Other
474 stars 169 forks source link

Add binary data support #17

Closed CaledoniaProject closed 3 years ago

CaledoniaProject commented 4 years ago

The current implementation works for string only, can you expose interface to encrypt and decrypt binary data?

It's not possible to encrypt bytes in Python 3 server and do decryption in C#, as the PKCS7 implementation supports str object only.

barbolo commented 3 years ago

If anyone else is also having a problem encrypting binary data in C#, the code below in aes256.cs should work:

public string Encrypt(byte[] data, string passphrase)
{
    using (var random = new RNGCryptoServiceProvider())
    {
        byte[] salt = new byte[8];
        random.GetBytes(salt);

        DeriveKeyAndIv(passphrase, salt);

        byte[] encrypted;
        using (var aes = new RijndaelManaged())
        {
            aes.BlockSize = BlockSize * 8;
            aes.Mode = CipherMode.CBC;
            aes.Padding = PaddingMode.PKCS7;
            aes.Key = key;
            aes.IV = iv;
            ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
            using (var msEncrypt = new MemoryStream())
            {
                using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                {
                    csEncrypt.Write(data, 0, data.Length);
                    csEncrypt.FlushFinalBlock();
                    encrypted = msEncrypt.ToArray();
                }
            }
        }

        return System.Convert.ToBase64String(Concat(Concat("Salted__", salt), encrypted));
    }
}

Then you use like:

byte[] data = File.ReadAllBytes("PATH_TO_BINARY_FILE");
string encrypted = aes.Encrypt(data, "PASSWORD");
CaledoniaProject commented 3 years ago

@barbolo Maybe you could submit a pull request. Also, please include a decrypt method for binary data.

barbolo commented 3 years ago

@CaledoniaProject I've submitted the PR here: https://github.com/mervick/aes-everywhere/pull/29