Skip to content Skip to sidebar Skip to footer

Java String Encrypt

I am using the encryption class in Objective C for my iPhone app but I am struggling to get the same functionality working in JAVA from my android app. My encryption code is below

Solution 1:

Here is a sample of encryption and decryption:

publicstatic SecretKey generateKey()throws NoSuchAlgorithmException, InvalidKeySpecException {
    returnsecret=newSecretKeySpec(password.getBytes(), "AES");
}

publicstaticbyte[] encryptMsg(String message, SecretKey secret) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidParameterSpecException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
/* Encrypt the message. */Ciphercipher=null;
    cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, secret);
    byte[] cipherText = cipher.doFinal(message.getBytes("UTF-8"));
    return cipherText;
}

publicstatic String decryptMsg(byte[] cipherText, SecretKey secret)throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidParameterSpecException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException {

    /* Decrypt the message, given derived encContentValues and initialization vector. */Ciphercipher=null;
    cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
   cipher.init(Cipher.DECRYPT_MODE, secret);
    StringdecryptString=newString(cipher.doFinal(cipherText), "UTF-8");
    return decryptString;
}

To encrypt:

    SecretKey secret = EncUtil.generateKey();
    EncUtil.encryptMsg(<Stringto Encrypt>, secret))

to decrypt

    EncUtil.decryptMsg(<byte[]>, secret))

Solution 2:

Instead of using ECB, you ought to use CBC or CTR if possible. ECB is insecure.

It looks like your Objective-C code is using UTF-8 encoding, but you're not specifying this in your Java code. Use getBytes("UTF-8").

Solution 3:

One thing that I've noticed that has caused problems in the past is that the iOS string being encrypted is actually "Hello World\0", eg the string to be encrypted with an extra null at the end. so try adding a \0 to the end of your string in Java and see if it produces the same results.

Additionally, the URLEncoder step on java may be introducing extra control characters and other things that are not present on the iOS side. It may be worthwhile to compare the text after this with the text going into the iOS encryption step to ensure that they are exactly the same

Post a Comment for "Java String Encrypt"