Encrypting and Decrypting String using a Java equilavent of the C# CryptoStream

Boardy picture Boardy · Jan 4, 2011 · Viewed 10.4k times · Source

I am looking at developing an application in Java for a mobile platform operating system.

I have developed an application in C# WPF for the Windows Environment. I am using a cryptostream in order to encrypt and decrypt a string using the following code. the code shown below is the encryption only

public string encrypt(string encryptionString)
    {
        byte[] clearTextBytes = Encoding.UTF8.GetBytes(encryptionString);

        SymmetricAlgorithm rijn = SymmetricAlgorithm.Create();

        MemoryStream ms = new MemoryStream();
        byte[] rgbIV = Encoding.ASCII.GetBytes("ryojvlzmdalyglrj");
        byte[] key = Encoding.ASCII.GetBytes("hcxilkqbbhczfeultgbskdmaunivmfuo");
        CryptoStream cs = new CryptoStream(ms, rijn.CreateEncryptor(key, rgbIV), CryptoStreamMode.Write);

        cs.Write(clearTextBytes, 0, clearTextBytes.Length);

        cs.Close();

        return Convert.ToBase64String(ms.ToArray());
    }

The encrypted string is stored in an online database. What I need to be able to do is for the java application to be able to read the string from the database and decrypt the string using the same encryption keys from the C# application.

Thanks for your help.

Answer

Cameron Skinner picture Cameron Skinner · Jan 4, 2011

Personally, I like BouncyCastle for Java crypto. This code (using the BouncyCastle lightweight API) should do the trick:

String decrypt(byte[] cryptoBytes, byte[] key, byte[] iv) {
    BlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()));
    cipher.init(false, new ParametersWithIV(new KeyParameter(key), iv));
    byte[] out = new byte[cipher.getOutputSize(cryptoBytes.length)];
    int offset = cipher.processBytes(cryptoBytes, 0, cryptoBytes.length, out, 0);
    cipher.doFinal(out, offset);
    return new String(out);
}

I find BouncyCastle's lightweight API to be less painful than the JCE provider stuff but you can use it as a provider if you wish.

It looks like both the .net SymmetricAlgorithm and BC's PaddedBufferedBlockCipher default to PKCS7 padding so you should be OK with using the defaults.