对于一个项目,尝试使用 DES 算法加密密码。
当我尝试这个
private static String key = "my8bcode"; /*Key 8 bytes or 56 bit supported by algo OF*/
private static byte[] byteKey = key.getBytes();
public static void main(String[] args) throws Exception {
String ss = "yuyuvdzdsfdsfsdsdsdsdsa";
byte[] plainText = ss.getBytes();//Conversion en byte
try {
SecretKeySpec secretKeySpec = new SecretKeySpec(byteKey, "DES");
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); // Request the use of the DES algorithm, using the ECB mode (Electronic CodeBook) and style padding PKCS-5.
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] myCipherText = cipher.doFinal(plainText);
System.out.println(new String(myCipherText, "UTF8"));
System.out.println(myCipherText.length);
System.out.println("\nStart decryption");
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
byte[] newPlainText = cipher.doFinal(myCipherText);
System.out.println(new String(newPlainText, "UTF8"));
} catch (Exception e) {
e.printStackTrace();
}
我没有问题,但为了更进一步,我尝试使用此代码分两个单独的步骤来执行此操作:
try {
SecretKeySpec secretKeySpec = new SecretKeySpec(byteKey, "DES");
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); //Request the use of the DES algorithm, using the ECB mode (Electronic CodeBook) and style padding PKCS-5.
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] myCipherText = cipher.doFinal(plainText);
byte[] test = (new String(myCipherText, "UTF8")).getBytes();
System.out.println("\nStart decryption");
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
byte[] newPlainText = cipher.doFinal(test);
System.out.println(new String(newPlainText, "UTF8"));
} catch (Exception e) {
e.printStackTrace();
}
它不起作用,我的控制台中显示此消息:
javax.crypto.IllegalBlockSizeException: Input length must be multiple of 8
确实,test[]的长度是7而不是8。怎么可能?
为什么我在转录过程中丢失了一个字节?
请帮助我理解并解决我的问题;)
最佳答案
byte[]
和 String
应分开。主要错误是随机字节序列(加密文本)很可能是不正确的 UTF-8。 UTF-8 是一种多字节格式,其中高位以指定方式标记多字节序列,例如 10xxxxxx
是连续字节。
但是,要加密字符串 (Unicode),使用 UTF-8 是非常合适的。单字节编码是有损的;说明文本是否同时包含希腊语和保加利亚语。
byte[] data = text.getBytes(StandardCharsets.UTF_8);
text = new String(data, StandardCharsets.UTF_8);
这些是来自 String
构造函数和 getBytes
方法的重载版本,并指定了字符集。否则它是依赖于平台的,因此与另一台计算机的通信是灾难性的。
但是一旦您有了二进制数据,byte[]
,就不要将其转换为 (Unicode) 字符串,这是一个(昂贵的)转换,冗余且容易出错。
因此,人们经常会看到二进制数据额外转换为 Base64,从而接收更长的 ASCII 字符串。
关于java - DES密文长度在传输过程中减少且不是8字节的倍数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30035313/