Android AES加密和解密

时间:2015-06-23 20:37:32

标签: android aes

我已经找到了数百个Android AES加密和解密的例子,但我无法让它们工作,即使是最简单的。下面的代码进行了一些加密和解密,但在解密加密文本后会吐出垃圾。你能看看我告诉我哪里错了吗?

由于

KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(128, new SecureRandom());
SecretKey secretKey = keyGenerator.generateKey();

Cipher cipher = Cipher.getInstance("AES");

String plainText = "This is supposed to be encrypted";
String plainKey = Base64.encodeToString(secretKey.getEncoded(), Base64.DEFAULT);

//encrypt
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
String encryptedText = Base64.encodeToString(encryptedBytes, Base64.DEFAULT);

//decrypt
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[]decryptedBytes = cipher.doFinal(encryptedBytes);
String decryptedText = Base64.encodeToString(decryptedBytes, Base64.DEFAULT);

2 个答案:

答案 0 :(得分:0)

@Barend回答有效: 你的代码运行正常。什么@greenapps说。而不是Base64.encodeToString(..),尝试打印新String(decryptedBytes)的输出,您将看到它是您正在寻找的值。

答案 1 :(得分:-1)

    SecretKeySpec sks = null;
    try {
        SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
        sr.setSeed("Complex Key for encryption".getBytes());
        KeyGenerator kg = KeyGenerator.getInstance("AES");
        kg.init(128, sr);
        sks = new SecretKeySpec((kg.generateKey()).getEncoded(), "AES");
    } catch (Exception e) {
        Log.e(TAG, "AES secret key spec error");
    }

    // Encode the original data with AES
    byte[] encodedBytes = null;
    try {
        Cipher c = Cipher.getInstance("AES");
        c.init(Cipher.ENCRYPT_MODE, sks);
        encodedBytes = c.doFinal(theTestText.getBytes());
    } catch (Exception e) {
        Log.e(TAG, "AES encryption error");
    }
    TextView tvencoded = (TextView)findViewById(R.id.textitem2);
    tvencoded.setText("[ENCODED]:\n" +
            Base64.encodeToString(encodedBytes, Base64.DEFAULT) + "\n");

    // Decode the encoded data with AES
    byte[] decodedBytes = null;
    try {
        Cipher c = Cipher.getInstance("AES");
        c.init(Cipher.DECRYPT_MODE, sks);
        decodedBytes = c.doFinal(encodedBytes);
    } catch (Exception e) {
        Log.e(TAG, "AES decryption error");
    }
    TextView tvdecoded = (TextView)findViewById(R.id.textitem3);
    tvdecoded.setText("[DECODED]:\n" + new String(decodedBytes) + "\n");