【问题标题】:AES Decryption not workingAES解密不起作用
【发布时间】:2012-03-08 15:26:36
【问题描述】:

在我的项目中,我正在研究 AES 加密和解密。我使用此算法加密和解密字符串并将字符串存储在 sq-lite 数据库中。现在我从数据库中获取加密密钥并尝试解密它但它显示一个异常(填充块损坏)。我正在使用

将加密字符串转换为字节
 public static byte[] hexStringToByteArray(String s) {
    int len = s.length();
    byte[] data = new byte[len / 2];
    for (int i = 0; i < len; i += 2) {
        data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                             + Character.digit(s.charAt(i+1), 16));}
    return data;
}

并获得正确的字节,但在转换为字符串时显示“垫块损坏”。 在此先感谢。如果找到答案,我将不胜感激。 我的代码是

dh=new data_helper(Resy.this);
        mac_db=dh.getData();

//        getdata=mac_db.toString();

        KeyGenerator kgen;
        try {
            kgen = KeyGenerator.getInstance("AES");

             kgen.init(128); // 192 and 256 bits may not be available

  // Generate the secret key specs.
                SecretKey skey = kgen.generateKey();
                byte[] raw = skey.getEncoded();

                SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");


                // Instantiate the cipher

                Cipher cipher = Cipher.getInstance("AES");
                         getdata=mac_db.toString();
//              byte g1[]=getdata.getBytes();
//              System.out.println(g1);

        byte b[]=hexStringToByteArray(getdata);
        cipher.init(Cipher.DECRYPT_MODE, skeySpec);
        byte[] m1=cipher.doFinal(b);   // here pad block corrupt exception came.
                String originalString_mac = new String(original_macadress);
                Toast.makeText(getApplicationContext(),"Original : " +originalString_mac + " " + asHex(original_macadress) , Toast.LENGTH_LONG).show();

【问题讨论】:

  • 零接受拉曼,先接受你之前问题的一些答案——答案太简单了,但直到你接受一些答案...
  • 仍然不明白为什么接受一个解决方案作为答案这么难。

标签: android aes


【解决方案1】:

首先确保您的数据长度正确,并且十六进制转换没有错误。接下来,您需要使用相同的密钥进行加密和解密。从上面的代码看来,您每次都在生成一个新密钥。这将不起作用:即使解密成功,您也会得到与原始纯文本非常不同的东西。然后Cipher cipher = Cipher.getInstance("AES"); 可能会使用随机 IV 生成密码,您需要对其进行解密。最好像这样指定一个显式的转换字符串:

Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");

简而言之,找到一个工作样本并从那里开始。类似this

【讨论】:

    【解决方案2】:

    您必须对其进行 Base64 编码才能使正确的 AES 加密/解密工作。

    按如下方式进行。

    对于加密:原始字符串 --> Aes 加密 > base64 编码 --->(加密字符串)

    用于解密:加密字符串--->base64解码>aes解密--->原始字符串

    【讨论】:

    • 你当然没有来使用 Base64——这只是将二进制 blob 转换为字符串的一种方法。十六进制编码或任何可逆的编码都可以。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-19
    • 1970-01-01
    • 2016-05-19
    相关资源
    最近更新 更多