我尝试解码时遇到错误。 这是解码器:
public class Encrypter {
Cipher ecipher;
Cipher dcipher;
SecretKeySpec key = new SecretKeySpec("missyou1".getBytes(), "DES");
public DesEncrypter() throws Exception {
ecipher = Cipher.getInstance("DES");
dcipher = Cipher.getInstance("DES");
ecipher.init(Cipher.ENCRYPT_MODE, key);
dcipher.init(Cipher.DECRYPT_MODE, key);
}
public String encrypt(String str) throws Exception {
byte[] utf8 = str.getBytes("UTF8");
byte[] enc = ecipher.doFinal(utf8);
return new sun.misc.BASE64Encoder().encode(enc);
}
public String decrypt(String str) throws Exception {
byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
byte[] asd = new byte[(dec.length/8+1)*8];
for(int i = 0; i < dec.length; i++){
asd[i] = dec[i];
}
byte[] utf8 = dcipher.doFinal(asd);
return new String(utf8, "UTF8");
}
}
这是我收到错误的代码:
private static void appenda(Encrypter encrypt) {
if (Files.exists(Paths.get(filePath), new LinkOption[] { LinkOption.NOFOLLOW_LINKS })) {
Stream<String> stringStream = null;
try {
stringStream = Files.lines(Paths.get(filePath), StandardCharsets.UTF_8);
} catch (IOException e) {
LOGGER.error("Failed ", e);
}
if (stringStream.toString() != null) {
stringStream.forEach(s -> {
try {
System.out.println(encrypt.decrypt(s));
endpoint.delete(0, endpoint.length());
endpoint.append(encrypt.decrypt(s));
} catch (Exception e) {
LOGGER.error("Failed to decrypt", e);
}
});
}
}
}
第endpoint.append(encrypter.decrypt(s));
行知道为什么吗?
答案 0 :(得分:0)
它不起作用,因为你不必要地将数据复制到一个大小不正确的数组中。
只需删除数组副本并直接解密字节。
public String decrypt(String str) throws Exception {
byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
byte[] utf8 = dcipher.doFinal(dec);
return new String(utf8, "UTF8");
}