I am using the following simple encrypt and decrypt functions just to see that it works before using more complicated security features like padding and hashing. For some reason the returned clear text is not similar to the original message. Here is the code:
public static byte[] encrypt(SecretKey secret, byte[] buffer) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidParameterSpecException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException
{
/* Encrypt the message. */
cipher = Cipher.getInstance("AES/CTR/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, secret);
byte[] ciphertext = cipher.doFinal(buffer);
return ciphertext;
}
public static byte[] decrypt(SecretKey secret, byte[] buffer) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidParameterSpecException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException
{
/* Decrypt the message. - use cipher instance created at encrypt */
cipher.init(Cipher.DECRYPT_MODE, secret);
byte[] clear = cipher.doFinal(buffer);
return clear;
}
and the calling code:
SecretKey secret1 = null;
byte[] ciphertext = null;
byte[] message = "Hello, World!".getBytes();
byte[] clear = null;
try {
// aSecret is a shared secret generated with ECDH
secret1 = Crypto.createAESKey(aSecret);
ciphertext = Crypto.encrypt(secret1, message);
clear = Crypto.decrypt(secret1, ciphertext);
String s = new String(clear);//clear.toString();
keyAText.setText(new String(message));
keyBText.setText(s);
return;
} catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidParameterSpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}