2015-11-02 115 views
0

我需要使用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; 
} 

回答

0

的工作,因爲這是進行加密,因爲它是在你的類,你可以使用此代碼的Java代碼。這是AES algorithm encryption,所以你只需要進行加密和解密

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

創建methods ...參考,你可以效仿的榜樣得到N- Aes encryption example