Question

Good Day, I need to encrypt some text using the base64 encoding and pass the encoded data to .NET application. The .NET application uses the following form of encoding & decoding. I have tried this Equivalent to CryptoStream .NET in Java?. I have used Apache commons codec for this purpose following the above link. But Stuck with the cryptoProvider.CreateEncryptor(bytes, bytes) , When i checked the third parameter in java equivalent -

Cipher.init(cipher.ENCRYPT_MODE,key,iv)

it must be an IvParameterSpec.I dont know how to solve this. Hope to get some help, Cheers!

.NET encryption

static byte[] bytes = ASCIIEncoding.ASCII.GetBytes("mykey");
public static string Encrypt(string originalString)
{        
    DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
    MemoryStream memoryStream = new MemoryStream();
    CryptoStream cryptoStream = new CryptoStream(memoryStream,cryptoProvider.CreateEncryptor(bytes, bytes), CryptoStreamMode.Write);
    StreamWriter writer = new StreamWriter(cryptoStream);
    writer.Write(originalString);
    writer.Flush();
    cryptoStream.FlushFinalBlock();
    writer.Flush();
    return Convert.ToBase64String(memoryStream.GetBuffer(), 0, (int)memoryStream.Length);
}

Equivalent

Java Encryption

void encrypt(String inputText) throws Exception {
    try {
        String myKey = "mykey";
        byte[] mybyte = str.getBytes("ASCII");
        //String plainIV = "1234567890ABCDEF";
        KeySpec keySpec = new DESKeySpec(myKey.getBytes("ASCII"));
        SecretKey key = SecretKeyFactory.getInstance("DES").generateSecret(keySpec);
        //IvParameterSpec iv = new IvParameterSpec(org.apache.commons.codec.binary.Hex.decodeHex(plainIV.toCharArray()));
        IvParameterSpec iv = new IvParameterSpec(mybyte);
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE,key,iv);
        byte[] encoded = cipher.doFinal(inputText.getBytes("ASCII"));   
        System.out.println("Encoded Value ..... "+Base64.encodeBase64(encoded));
    } catch(UnsupportedEncodingException e) {
        System.out.println("Exception .. "+ e.getMessage());
    }

In .Net i get this- AOb0B20x2onFGz+JaFBsZyFbvCS9WF49D as the encoded value but in java, I'm getting wired encoded string- =�SKNv?�N�Ɛq{���U�;�/Z���8��<

Edit:-

Followed zacheusz and solved encoding problem, but encoded strings in both .NET and java are different...

Was it helpful?

Solution

I see that in .NET you are specyfing IV:

cryptoProvider.CreateEncryptor(bytes, bytes)

According to the documentation the second byte array is the IV. So you should use the same array in Java.

I think that the bug is here:

cipher.doFinal(Base64.encodeBase64(inputText.getBytes("ASCII"))); 

You are b64 encoding input before decrypting it.

Try

    byte[] output = cipher.doFinal(inputText.getBytes("ASCII"));  
    System.out.println("Encoded Value ..... "+new String(Base64.encodeBase64(output)));

Additional remarks (regarding your questions in comments):

OTHER TIPS

Thank you @zacheusz, I got it!!! It was a silly mistake,I was printing the byte[] value, i forget to convert it to String

So Changed

System.out.println("Encoded Value ..... "+Base64.encodeBase64(encoded));

To

System.out.println("Encoded Value ..... "+new String(Base64.encodeBase64(encoded),"ASCII");

and That Solved my problem. Also modified code with ByteArrayOutputStream. Here is the Encoding & Decoding functions

String encrypt(String inputText) throws Exception {
    byte[] keyValue = new byte[] { 'm', 'y', 'k', 'e', 'y', 'n', 'u', 'l'};
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    try {           
        KeySpec keySpec = new DESKeySpec(keyValue);
        SecretKey key = SecretKeyFactory.getInstance("DES").generateSecret(keySpec);
        IvParameterSpec iv = new IvParameterSpec(keyValue);
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding"); 
        cipher.init(Cipher.ENCRYPT_MODE,key,iv);
        bout.write(cipher.doFinal(inputText.getBytes("ASCII")));                        
    } catch(Exception e) {
        System.out.println("Exception .. "+ e.getMessage());
    }
    return new String(Base64.encodeBase64(bout.toByteArray()),"ASCII");
}

String decrypt(String inputText) throws Exception {
    byte[] keyValue = new byte[] { 'm', 'y', 'k', 'e', 'y', 'n', 'u', 'l'};
    try {
        KeySpec keySpec = new DESKeySpec(keyValue);
        SecretKey key = SecretKeyFactory.getInstance("DES").generateSecret(keySpec);
        IvParameterSpec iv = new IvParameterSpec(keyValue);

        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE,key,iv);
        //byte[] decoded = Base64.decodeBase64(inputText); //Works with apache.commons.codec-1.8
        byte[] decoded = Base64.decodeBase64(inputText.getBytes("ASCII"));// works with apache.commons.codec-1.3
        bout.write(cipher.doFinal(decoded));
    } catch(Exception e) {
        System.out.println("Exception ... "+e);
    }
    return new String(bout.toByteArray(),"ASCII");
}

Hope Someone will find it helpful...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top