DES对称加密错误

前提:
  • java
  • DES对称加密
错误描述:
  • Input length must be multiple of 8 when decrypting with padded cipher
错误分析:

在本地做了如下测试,发现解密时报错;

    String beforeStr = Tools.encodeData(Boolean.TRUE, "{\"data\":[\"370786********0915\"]}", config);
    System.out.println(beforeStr);

    String afterStr = Tools.decodeData(Boolean.TRUE, beforeStr, config);
    System.out.print(afterStr);

解密的方法如下:
如参是byte,比较加密后一步的byte和解密前一步的byte,发现长度不一致;

 public static byte[] decryptByDES(byte[] content, String key) {
    DESKeySpec dks;
    try {
        dks = new DESKeySpec(key.getBytes());
        SecretKeyFactory skf = SecretKeyFactory.getInstance(ALGORITHM_DES);
        SecretKey sk = skf.generateSecret(dks);
        Cipher cip = Cipher.getInstance(CIPHER_DES_PADDING);
        cip.init(Cipher.DECRYPT_MODE, sk);
        return cip.doFinal(content);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
问题解决:
  • 发现是将string转换成byte时导致,指定编码格式后解决;

    data.getBytes("UTF-8")

你可能感兴趣的:(DES对称加密错误)