使用密钥加密消息

时间:2015-11-02 09:04:05

标签: android encryption

我需要使用Android中的密钥加密邮件。

如何将以下代码转换为适用于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;
}

1 个答案:

答案 0 :(得分:0)

因为这是用于加密的 java 代码,所以您可以像使用此类代码一样使用此代码。这是AES algorithm encryption,因此您只需创建methods进行加密和解密

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;
}

...作为参考,你可以按照给出的例子 - Aes encryption example