0

I need to encrypt a message using a key in Android.

How can I convert the below code to work with Android

    public static String EncryptData(byte[] key, byte[] msg)
        throws Exception {
    String encryptedData = "";

    AESKey key = new AESKey(keyData);
    NoCopyByteArrayOutputStream out = new NoCopyByteArrayOutputStream();
    AESEncryptorEngine engine = new AESEncryptorEngine(key);
    BlockEncryptor encryptor = new BlockEncryptor(engine, out);
    encryptor.write(data, 0, data.length);
    int finalLength = out.size();

    byte[] cbytes = new byte[finalLength];
    System.arraycopy(out.getByteArray(), 0, cbytes, 0, finalLength);
    encryptedData = getHexString(cbytes);

    return encryptedData;
}
user1382802
  • 618
  • 2
  • 12
  • 24

1 Answers1

0

as this is java code for encryption you can use this code as it is in your class . this is AES algorithm encryption so you just need to create methods for encryption and decryption

private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(clear);
return encrypted;
}

private static byte[] decrypt(byte[] raw, byte[] encrypted) throws   
 Exception   {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decrypted = cipher.doFinal(encrypted);
return decrypted;
}

... for reference you can follow the example given- Aes encryption example

Community
  • 1
  • 1
sud
  • 505
  • 1
  • 4
  • 12