RaceBase
RaceBase

Reputation: 18848

Decrypting AES from C#, Encrypted from Java

We are using below code to encrypt in Java

public encrypt(String text) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidKeySpecException {
    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    KeySpec spec = new PBEKeySpec(passPhrase.toCharArray(), SALT, ITERATION_COUNT, KEY_LENGTH); //256 bit
    SecretKey tmp = factory.generateSecret(spec);
    SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
    this.ecipher = Cipher.getInstance("AES");
    this.ecipher.init(Cipher.ENCRYPT_MODE, secret);
    byte[] bytes = encrypt.getBytes("UTF-8");
    byte[] encrypted = this.ecipher.doFinal(bytes);
    return Base64.encodeBase64String(encrypted);
}

Our vendor is using C# to decrypt the data His code

string Decrypt(string textToDecrypt, string key)
{
    RijndaelManaged rijndaelCipher = new RijndaelManaged();
    rijndaelCipher.Mode = CipherMode.ECB;
    rijndaelCipher.KeySize = 0x80;
    rijndaelCipher.BlockSize = 0x80;
    byte[] encryptedData = Convert.FromBase64String(textToDecrypt);
    byte[] pwdBytes = Encoding.UTF8.GetBytes(key);
    byte[] keyBytes = new byte[0x10];
    int len = pwdBytes.Length;
    if (len > keyBytes.Length) {
        len = keyBytes.Length;
    }
    Array.Copy(pwdBytes, keyBytes, len);
    rijndaelCipher.Key = keyBytes;
    byte[] plainText = rijndaelCipher.CreateDecryptor().TransformFinalBlock(encryptedData, 0, encryptedData.Length);
    return Encoding.UTF8.GetString(plainText); 
}

But he's unable to decrypt the data. He's getting some garbage data. Any idea how to decrypt using C# for Java Encryption part.

Upvotes: 0

Views: 900

Answers (1)

jbtule
jbtule

Reputation: 31799

First off, Don't have any allusions of security with your java code. ECB mode not a good choice.

Second, the problem with the C# code is that it's using the raw bytes of the passphase for the key rather than PBKDF2WithHmacSHA1 which the java code is using. The class in C# to do the key generation is Rfc2898DeriveBytes

Upvotes: 3

Related Questions