gpt4 book ai didi

java - java中的填充异常和解密

转载 作者:行者123 更新时间:2023-12-01 15:24:11 26 4
gpt4 key购买 nike

我必须解密服务器上的一个帧。加密帧通过套接字上的 GPRS 来自客户端设备。加密是使用“TripleDes”和给定 key 完成的。我在服务器端使用相同的算法和 key 。框架是十六进制和 Ascii 字符串的组合。问题是当我解密此帧时出现错误:

javax.crypto.IllegalBlockSizeException: Input length must be multiple of 8 when decrypting with padded cipher

当我用零填充字节数组时,例如

temparray[87] = 00;

我收到错误:

javax.crypto.BadPaddingException: Given final block not properly padded

以下是我的代码:

if ((len = inputStream.read(mainBuffer)) > -1) {
totalLength = len;
}
if (totalLength > 0) {
byteToAscii = function.byteToAscii(mainBuffer, totalLength);
}
if (byteToAscii.length() > 0) {
completeHexString = function.stringToHex(byteToAscii);
debugInfo = "FRAME RECV.=" + completeHexString;
/* FRAME RECV.=41ed34a41a9de6d270aa1e1464527e88c8bee66a00cfb308f60c105de81db0f1ce43d8c0b9bc4e8070b5ab8d4d3650b55d23223fc687bb1485945bc3228e9707a7aecda9f90657e0ac009571c6469c58a2cd9793cc433ccb5993f2*/
}
byte[] key = new byte[]{31, 30, 31, 36, 32, 11, 11, 11, 22, 26, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30};
myKeySpec = new DESedeKeySpec(key);
mySecretKeyFactory = SecretKeyFactory.getInstance("TripleDES");
dekey = mySecretKeyFactory.generateSecret(myKeySpec);
byte[] zeros = {0, 0, 0, 0, 0, 0, 0, 0};
IvParameterSpec iv = new IvParameterSpec(zeros);
Cipher c = Cipher.getInstance("TripleDES/CBC/PKCS5Padding");
c.init(Cipher.DECRYPT_MODE, key, iv);
byte[] decordedValue = new BASE64Decoder().decodeBuffer(completeHexString);
byte[] decValue = c.doFinal(decordedValue);
String decryptedValue = new String(decValue);
System.out.println("decryptedValue= " + decryptedValue);

这是我在代码中使用的函数:

public String stringToHex(String base) {
StringBuffer buffer = new StringBuffer();
int intValue = 0;
for (int x = 0; x < base.length(); x++) {
intValue = base.charAt(x);
String hex = Integer.toHexString(intValue);
if (hex.length() == 1) {
buffer.append("0" + hex + "");
} else {
buffer.append(hex + "");
}
}
return buffer.toString();
}
public String byteToAscii(byte[] b, int length) {
String returnString = "";
for (int i = 0; i < length; i++) {
returnString += (char) (b[i] & 0xff);
}
return returnString;
}

我是 Java 密码学新手。请告诉我该怎么做?提前致谢。

最佳答案

PKCS5 填充字节值必须是填充字节数。例如,如果要填充 5 个字节,则填充将为 05 05 05 05 05。如果需要填充两个字节,则填充将为 02 02

关于java - java中的填充异常和解密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10412771/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com