這是使用真正加密的一個非常簡短的例子。這是128位AES,它非常安全 - 當然不能被任何想象中的可讀性所讀取。
它會生成一個隨機密鑰,所以每次運行都會有所不同。您需要分享他們之間交換數據的兩個程序之間的密鑰。
private static final String ENCRYPTION_ALGORITHM = "AES/ECB/PKCS5Padding";
private static final SecureRandom RANDOM = new SecureRandom();
public static void main(String[] args) throws UnsupportedEncodingException, GeneralSecurityException {
final KeyGenerator keyGen = KeyGenerator.getInstance(ENCRYPTION_ALGORITHM.substring(0, ENCRYPTION_ALGORITHM.indexOf('/')));
keyGen.init(128, RANDOM);
final SecretKey key = keyGen.generateKey();
final String s = "My topsecret string";
System.out.println(s);
final Cipher encryption = getCipher(key, Cipher.ENCRYPT_MODE);
final String enc = DatatypeConverter.printBase64Binary(encryption.doFinal(s.getBytes("UTF-8")));
System.out.println(enc);
final Cipher decryption = getCipher(key, Cipher.DECRYPT_MODE);
final String dec = new String(decryption.doFinal(DatatypeConverter.parseBase64Binary(enc)), "UTF-8");
System.out.println(dec);
}
private static Cipher getCipher(final Key key, final int mode) throws GeneralSecurityException {
final Cipher cipher = Cipher.getInstance(ENCRYPTION_ALGORITHM);
cipher.init(mode, key, RANDOM);
return cipher;
}
輸出:
My topsecret string
ip4La5KUBJGTTYenoE920V5w0VBHwALv4fp3qyLTY9o=
My topsecret string
Base_64是人類可讀的嗎?嗯,你知道一些聰明的人。 – jn1kk 2013-04-26 14:14:52
爲了安全地公開分享加密信息,您需要共享密碼或公鑰/私鑰加密。請詳細說明您實際需要防範的威脅。休閒閱讀?更強大的東西? – 2013-04-26 14:15:10
http://stackoverflow.com/questions/8622367/what-are-best-practices-for-using-aes-encryption-in-android?rq=1 – durron597 2013-04-26 14:16:46