使用AES算法进行加密和解密

时间:2014-07-23 11:07:25

标签: java android encryption cryptography

我正在为我的应用程序制作加密/解密模块。我跟着This Tutorial

它没有给出任何错误,也没有显示输出。

日志文件

07-23 07:29:06.480: W/System.err(795): javax.crypto.BadPaddingException: pad block corrupted
07-23 07:29:06.629: W/System.err(795):  at com.android.org.bouncycastle.jcajce.provider.symmetric.util.BaseBlockCipher.engineDoFinal(BaseBlockCipher.java:710)
07-23 07:29:06.629: W/System.err(795):  at javax.crypto.Cipher.doFinal(Cipher.java:1111)
07-23 07:29:06.660: W/System.err(795):  at com.example.generatesha384.AESHelper.decrypt(AESHelper.java:52)
07-23 07:29:06.690: W/System.err(795):  at com.example.generatesha384.AESHelper.decrypt(AESHelper.java:25)
07-23 07:29:06.690: W/System.err(795):  at com.example.generatesha384.MainActivity.onCreate(MainActivity.java:24)
07-23 07:29:06.700: W/System.err(795):  at android.app.Activity.performCreate(Activity.java:5133)
07-23 07:29:06.730: W/System.err(795):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
07-23 07:29:06.730: W/System.err(795):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
07-23 07:29:06.770: W/System.err(795):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
07-23 07:29:06.770: W/System.err(795):  at android.app.ActivityThread.access$600(ActivityThread.java:141)
07-23 07:29:06.770: W/System.err(795):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
07-23 07:29:06.800: W/System.err(795):  at android.os.Handler.dispatchMessage(Handler.java:99)
07-23 07:29:06.800: W/System.err(795):  at android.os.Looper.loop(Looper.java:137)
07-23 07:29:06.840: W/System.err(795):  at android.app.ActivityThread.main(ActivityThread.java:5103)
07-23 07:29:06.840: W/System.err(795):  at java.lang.reflect.Method.invokeNative(Native Method)
07-23 07:29:06.872: W/System.err(795):  at java.lang.reflect.Method.invoke(Method.java:525)
07-23 07:29:06.880: W/System.err(795):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
07-23 07:29:06.910: W/System.err(795):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
07-23 07:29:06.910: W/System.err(795):  at dalvik.system.NativeStart.main(Native Method)

MainActivity.Java

String seedValue = "This Is MySecure";

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    TextView text = (TextView)findViewById(R.id.result);

    String normalText = "VIJAY";
    String normalTextEnc;

    try {
        normalTextEnc = AESHelper.encrypt(seedValue, normalText);
        String normalTextDec = AESHelper.decrypt(seedValue, normalTextEnc);

        String textResult = "Normal Text ::" + normalText
                + " \n Encrypted Value :: " + normalTextEnc
                + " \n Decrypted value :: " + normalTextDec;
        text.setText(textResult);

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

AESHelper.Java

public class AESHelper {

public static String encrypt(String seed, String cleartext)
        throws Exception {
    byte[] rawKey = getRawKey(seed.getBytes("UTF-8"));
    byte[] result = encrypt(rawKey, cleartext.getBytes("UTF-8"));
    return toHex(result);
}

public static String decrypt(String seed, String encrypted)
        throws Exception {
    byte[] rawKey = getRawKey(seed.getBytes("UTF-8"));
    byte[] enc = toByte(encrypted);
    byte[] result = decrypt(rawKey, enc);
    return new String(result);
}

private static byte[] getRawKey(byte[] seed) throws Exception {
    KeyGenerator kgen = KeyGenerator.getInstance("AES");
    SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
    sr.setSeed(seed);
    kgen.init(128, sr); // 192 and 256 bits may not be available
    SecretKey skey = kgen.generateKey();
    byte[] raw = skey.getEncoded();
    return raw;
}

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);
    Log.d("DEC", "Decrypted: " + decrypted);
    return decrypted;
}

public static String toHex(String txt) {
    return toHex(txt.getBytes());
}

public static String fromHex(String hex) {
    return new String(toByte(hex));
}

public static byte[] toByte(String hexString) {
    int len = hexString.length() / 2;
    byte[] result = new byte[len];
    for (int i = 0; i < len; i++)
        result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2),
                16).byteValue();
    return result;
}

public static String toHex(byte[] buf) {
    if (buf == null)
        return "";
    StringBuffer result = new StringBuffer(2 * buf.length);
    for (int i = 0; i < buf.length; i++) {
        appendHex(result, buf[i]);
    }
    return result.toString();
}

private final static String HEX = "0123456789ABCDEF";

private static void appendHex(StringBuffer sb, byte b) {
    sb.append(HEX.charAt((b >> 4) & 0x0f)).append(HEX.charAt(b & 0x0f));
}

}

AESHelper.java:52

        byte[] decrypted = cipher.doFinal(encrypted);

和AESHelper.java:25

        byte[] result = decrypt(rawKey, enc);

1 个答案:

答案 0 :(得分:0)

在花费大量时间研究Java中的AES加密/解密之后,我将以下文章放在我在StackOverflow上阅读的所有信息 - http://netnix.org/2015/04/19/aes-encryption-with-hmac-integrity-in-java/

也许它有所帮助,也许它没有。