我尝试从编码解码十六进制结果但不成功 字符串编码:9041 解码后的字符串是[B @ 1f2be27 请帮帮我。
public static void main(String[] args) throws Exception {
String text = "FEBA4C2EDD47FD32";
String encode = encryptData("9041","747062616e6b6570696e6e6577696e746567726174696f6e",168,true);
String result = decryptData("FEBA4C2EDD47FD32", "747062616e6b6570696e6e6577696e746567726174696f6e", 168, false);
System.out.println(encode);
System.out.println(result); // this is a byte array, you'll just see a reference to an array
}
// endcode功能 public static String encryptData(String plainText,String key,int keySize,boolean paddingEnable) 抛出异常{ byte [] clearData = plainText.getBytes(); return encryptData(clearData,key,keySize,paddingEnable); }
public static String encryptData(byte[] clearData, String key, int keySize, boolean paddingEnable)
throws Exception {
byte[] keyBytes = getEncryptionKey(key, keySize);
SecretKey secretKey = new SecretKeySpec(keyBytes, "DESede");
String algo = "DESede/ECB/pkcs5padding";
Cipher cipher = Cipher.getInstance(algo);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] cipherText = cipher.doFinal(clearData);
System.out.println(clearData.toString());
return String.valueOf(Hex.encodeHex(cipherText, false));
}
public static String decryptData(String clearData, String key, int keySize, boolean paddingEnable)
throws Exception {
byte[] keyBytes = getEncryptionKey(key, keySize);
SecretKey secretKey = new SecretKeySpec(keyBytes, "DESede");
String algo = "DESede/ECB/pkcs5padding";
Cipher cipher = Cipher.getInstance(algo);
byte[] stringDecode = Hex.decodeHex(clearData.toCharArray());
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] cipherText = cipher.doFinal(stringDecode);
return cipherText.toString();
}
private static byte[] getEncryptionKey(String keyString, int keySize)
throws Exception {
int keyLength = keyString.length();
switch (keySize) {
case 56:
if (keyLength != 16) {
throw new InvalidKeyException("Hex Key length should be 16 for a 56 Bit Encryption, found [" + keyLength + "]");
}
break;
case 112:
if (keyLength != 32) {
throw new InvalidKeyException("Hex Key length should be 32 for a 112 Bit Encryption, found[" + keyLength + "]");
}
break;
case 168:
if ((keyLength != 32) && (keyLength != 48)) {
throw new InvalidKeyException("Hex Key length should be 32 or 48 for a 168 Bit Encryption, found[" + keyLength + "]");
}
if (keyLength == 32) {
keyString = keyString + keyString.substring(0, 16);
}
break;
default:
throw new InvalidKeyException("Invalid Key Size, expected one of [56, 112, 168], found[" + keySize + "]");
}
return Hex.decodeHex(keyString.toCharArray());
}
答案 0 :(得分:1)
在decryptData()
结束时,您有return cipherText.toString();
从字节数组本身的toString()
类调用Object
。这不是一个非常有趣的toString()
实现 - 它只是根据字节数组对象的内存中的位置返回一些垃圾。
您需要将字节数组实际转换回String
。你可以试试
return new String(cipherText);
作为decryptData()
的最后一行。