I have some code that is working correctly in Java but when I try to use it in Android it is having problems.
I am attempting to encrypt an SMS text message with the Blowfish algorithm.
The problem with this code (on android) is that it will not accept the byte[] and will not decrypt the message.
SENDING THE SMS
sMessage = "hello this is a message"
byte[] byteArray = EncryptBlowfish(sMessage);
//Convert the byte[] into a String which can be sent over SMS
StringBuffer strb = new StringBuffer();
for( int x = 0; x<byteArray.length; x++){
strb.append(byteArray[x]).append(",");
}//for loop
sMessage = strb.toString();
(sMessage is then sent via SMS)
RECIVING THE SMS
//Convert the String back to a byte[] which can be decrypted
String[] strArray = sMessage.split(",");
byte[] byteArray = new byte[strArray.length];
int hold;
for (int x = 0; x < strArray.length; x++) {
hold = Integer.parseInt(strArray[x]);
byteArray[x] = (byte) hold;
}//for loop
sMessage = DecryptBlowfish(byteArray);
Encryption Method
public static byte[] EncryptBlowfish(String msg){
byte[] encrypted =null;
try {
Cipher cipher = Cipher.getInstance("Blowfish");
cipher.init(Cipher.ENCRYPT_MODE, secretkey);
encrypted = cipher.doFinal(msg.getBytes());
} catch (){ //NoSuchAlgorithmException, NoSuchPaddingException..etc
}
return encrypted;
}
Decryption Method
public static String DecryptBlowfish(byte[] msg){
byte[] decrypted =null;
try {
Cipher cipher = Cipher.getInstance("Blowfish");
cipher.init(Cipher.DECRYPT_MODE, secretkey);
decrypted = cipher.doFinal(msg);
} catch (){ //NoSuchAlgorithmException, NoSuchPaddingException..etc
}
return decrypted;
}
The message is being encrypted, this creates a byte[], I have then converted the byte[] to a string, the string’s output will look something like this…
46,77,52,11,-108,91,-106,88,-81,-43,14,111,-118,-128,-92,-50,69,-44,100,-94,71,92,-49,116,
this output is then sent over SMS. The string is then convert back into a byte[]
but this byte array is not decrypting.
Questions:
- Why would this code work in a Java app, but not Android?
- Is there a way of making this work in Android?
- Is there a better method of converting the byte[] to a String and back.
(Please comment if anymore information is require, Thanks)
I think the answer involves what the default character encoding is on Android vs standard Java. What happens if you specify the character encoding using msg.getBytes(Charset c), and for decoding new String(byte [], Charset c).
Example:
You can find what character sets are available from: