java - 使用AES算法加密和解密

标签 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);

最佳答案

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

也许有帮助,也许没有。

关于java - 使用AES算法加密和解密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24908826/

相关文章:

java - 使用 jsoup 提交搜索查询

java - Spring 安全: At which point do I get to know that a user logged in?

java - Java 中的 ROT-N(或 ROT-X)函数

c# - 基于 FIPS 186-2 的伪随机数生成器

android - 如何停止在android中加载webview

java - JAVA 中的 WebSocket SSL

java - TextField 中的负数错误

java - 如何将这个 while 循环转换为 for 循环?

android - Oreo (8.1) 上的 toast 重叠问题

javascript - 在 Android 应用程序的谷歌地图上放置数千个图钉