Hello all,

I have a code to encrypt data in C# and I want it to b decrypted in Java...

following is the C# code

string Encrypt(string textToEncrypt, string key)
{
RijndaelManaged rijndaelCipher = new RijndaelManaged();
rijndaelCipher.Mode = CipherMode.CBC;
rijndaelCipher.Padding = PaddingMode.PKCS7;

rijndaelCipher.KeySize = 0x80;
rijndaelCipher.BlockSize = 0x80;
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;
rijndaelCipher.IV = keyBytes;
ICryptoTransform transform = rijndaelCipher.CreateEncryptor();
byte[] plainText = Encoding.UTF8.GetBytes(textToEncrypt);
return Convert.ToBase64String(transform.TransformFinalBlock(plainText, 0, plainText.Length)); 
}

and the java decryption is as follows...

String Decrypt(String text, String key) throws Exception{
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] keyBytes= new byte[16];
byte[] b= key.getBytes("UTF-8");
int len= b.length;
if (len > keyBytes.length) len = keyBytes.length;
System.arraycopy(b, 0, keyBytes, 0, len);
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
IvParameterSpec ivSpec = new IvParameterSpec(keyBytes);
cipher.init(Cipher.DECRYPT_MODE,keySpec,ivSpec);

BASE64Decoder decoder = new BASE64Decoder();
byte [] results = cipher.doFinal(decoder.decodeBuffer(text));
return new String(results,"UTF-8");
}

In this i am getting bad padding exception....where am I goin wrong??

plz help


String key = "testKey"; is the key

Does this make a difference? (PKCS7 vs PKCS5Padding):

rijndaelCipher.Padding = PaddingMode.PKCS7;

and...

Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

well there is no PKCS5 padding in C# and PKCS7 in Java... :(

how to go about this I want to know

Hello all
I found the solution for the above problem. I did it in little different way here is the C# code

public class TripleDESImplementation
    {
        //Encryption Key
        private byte[] EncryptionKey { get; set; }
        // The Initialization Vector for the DES encryption routine
        private byte[] IV { get; set; }

       
        /// Constructor for TripleDESImplementation class
        /// </summary>
        /// <param name="encryptionKey">The 24-byte encryption key (24 character ASCII)</param>
        /// <param name="IV">The 8-byte DES encryption initialization vector (8 characters ASCII)</param>
        public TripleDESImplementation(string encryptionKey, string IV)
        {
            if (string.IsNullOrEmpty(encryptionKey))
            {
                throw new ArgumentNullException("'encryptionKey' parameter cannot be null.", "encryptionKey");
            }
            if (string.IsNullOrEmpty(IV))
            {
                throw new ArgumentException("'IV' parameter cannot be null or empty.", "IV");
            }

            EncryptionKey = Encoding.ASCII.GetBytes(encryptionKey);
            // Ensures length of 24 for encryption key
            Trace.Assert(EncryptionKey.Length == 24, "Encryption key must be exactly 24 characters of ASCII text (24 bytes)");

            this.IV = Encoding.ASCII.GetBytes(IV);
            // Ensures length of 8 for init. vector
            Trace.Assert(IV.Length == 8, "Init. vector must be exactly 8 characters of ASCII text (8 bytes)");
        }

       
        /// Encrypts a text block

        public string Encrypt(string textToEncrypt)
        {
            TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
            tdes.Key = EncryptionKey;
            tdes.IV = IV;

            byte[] buffer = Encoding.ASCII.GetBytes(textToEncrypt);
            return Convert.ToBase64String(tdes.CreateEncryptor().TransformFinalBlock(buffer, 0, buffer.Length));
        }

       
        /// Decrypts an encrypted text block
       
        public string Decrypt(string textToDecrypt)
        {
            byte[] buffer = Convert.FromBase64String(textToDecrypt);

            TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
            des.Key = EncryptionKey;
            des.IV = IV;

            return Encoding.ASCII.GetString(des.CreateDecryptor().TransformFinalBlock(buffer, 0, buffer.Length));
        }
    }

    }

the above encryption can be decrypted by following Java code...

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class TripleDES {
private String key;
private String initializationVector;
public TripleDES(String key, String initializationVector)
{
this.key = key;
this.initializationVector = initializationVector;

}

public String encryptText(String plainText) throws Exception{
//---- Use specified 3DES key and IV from other source --------------
byte[] plaintext = plainText.getBytes();
byte[] tdesKeyData = key.getBytes();

// byte[] myIV = initializationVector.getBytes();

Cipher c3des = Cipher.getInstance("DESede/CBC/PKCS5Padding");
SecretKeySpec myKey = new SecretKeySpec(tdesKeyData, "DESede");
IvParameterSpec ivspec = new IvParameterSpec(initializationVector.getBytes());

c3des.init(Cipher.ENCRYPT_MODE, myKey, ivspec);
byte[] cipherText = c3des.doFinal(plaintext);

return new sun.misc.BASE64Encoder().encode(cipherText);
}
public String decryptText(String cipherText)throws Exception{
byte[] encData = new sun.misc.BASE64Decoder().decodeBuffer(cipherText);
Cipher decipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
byte[] tdesKeyData = key.getBytes();
SecretKeySpec myKey = new SecretKeySpec(tdesKeyData, "DESede");
IvParameterSpec ivspec = new IvParameterSpec(initializationVector.getBytes());
decipher.init(Cipher.DECRYPT_MODE, myKey, ivspec);
byte[] plainText = decipher.doFinal(encData);
return new String(plainText);
}
}

use keys as

"4d89g13j4j91j27c582ji693" (which is a random key)

and IV as 'abhijeet'

hope it helps..:)

this decrytion method faces the following exception when the cipher'd length is a multiple of 8;

Input length must be multiple of 8 when decrypting with padded cipher

what should be done to have it fixed?
tnx

first of all: you shouldn't have re-started a thread that was solved a year ago, you should've started your own.

show what you have (not the above code) and say what problems you are having with it.

thanks bro.. although i found number of posts like this but none helped me except your post.. thanks bro.

can you please tell encryption in java and decryption in C#

commented: the question was answered by the OP shortly after asking the question. Think it's time for a career change manoj -2
commented: Not answered at all. Original was the other way round. +14

Manoj: don't hijack old topics. Start you own.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.