【问题标题】:Decryption of AES encrypted field in javajava中AES加密字段的解密
【发布时间】:2014-01-21 06:02:05
【问题描述】:

我试图用 java 加密一个字段,但我无法解密它。

我不是在发送数据,我只是希望它在插入时加密并在检索时解密。

我使用了这段代码,但解密不起作用。

public void setkey() throws Exception {
    byte[] key1 = new String("abcd").getBytes("UTF-8"); // some logic will replace "abcd"
     MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");
     key1 = messageDigest.digest(key1);
     key1 = Arrays.copyOf(key1,16);
     key = key1;
     //this key must be the same when encrypting and decrypting, right?
}

@Override
public String encryptField(Myclass myClass) throws Exception {

    Cipher cipher = Cipher.getInstance("AES");
    SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
    cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
    String encryptedField = Base64.encodeBase64String(cipher.doFinal(myClass.myField.getBytes("UTF-8")));
    myClass.setMyField(encryptedField);
    save(myClass);

    return encryptedField;
    //this looks OK, and gives me 24 character string.
}


@Override
public String decryptVoucher(Myclass myClass) throws Exception {

    String skey = key.toString();
    Cipher cipher = Cipher.getInstance("AES");
    SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
    cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
    byte[] decryptedField = cipher.doFinal(Base64.decodeBase64(yClass.myField.getBytes("UTF-8")));
    // decryptedField.toString() is not as same as original data...
    return decryptedField.toString();
}

ps:我已经搜索并阅读了thisthis,实际上我是在他们的帮助下来到这里的。

【问题讨论】:

    标签: java encryption


    【解决方案1】:

    问题是您在字节数组上调用toString 方法。 toString 为您提供数组对象的字符串表示形式;它不会尝试将数组的内容转换为字符串。您看到的输出类似于“[B@798b429b”,对吧?

    要将解密的字节转换为字符串对象,请使用new String(decryptedField, "UTF-8")。这将正确地将字节转换为字符。

    请记住,Java 无法知道字节数组包含表示字符的数据。 Array 类上的 toString 方法返回数组的描述,而不是其内容。它使用默认的toString 实现,即:

    getClass().getName() + '@' + Integer.toHexString(hashCode())
    

    (来自http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#toString%28%29

    在这种情况下,类名是“[B”,意思是“字节数组”。

    【讨论】:

      猜你喜欢
      • 2013-04-19
      • 2019-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-01
      • 2022-10-16
      • 2016-01-04
      • 1970-01-01
      相关资源
      最近更新 更多