如何解决DESede-ECB 加解密
我正在尝试使用以下代码在 java 中加密和解密字符串:
public byte[] encrypt(String message) throws Exception {
final MessageDigest md = MessageDigest.getInstance("md5");
final byte[] digestOfPassword = md.digest("MYKEY12345"
.getBytes("utf-8"));
final byte[] keyBytes = Arrays.copyOf(digestOfPassword,24);
for (int j = 0,k = 16; j < 8;) {
keyBytes[k++] = keyBytes[j++];
}
final SecretKey key = new SecretKeySpec(keyBytes,"DESede");
// final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
final Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE,key);
final byte[] plainTextBytes = message.getBytes("utf-8");
final byte[] cipherText = cipher.doFinal(plainTextBytes);
// final String encodedCipherText = new sun.misc.BASE64Encoder()
// .encode(cipherText);
Log.d("base64",Base64.getEncoder().encodeToString(cipherText));
return cipherText;
}
public String decrypt(byte[] message) throws Exception {
final MessageDigest md = MessageDigest.getInstance("md5");
final byte[] digestOfPassword = md.digest("MYKEY12345"
.getBytes("utf-8"));
final byte[] keyBytes = Arrays.copyOf(digestOfPassword,"DESede");
// final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
final Cipher decipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
decipher.init(Cipher.DECRYPT_MODE,key);
// final byte[] encData = new
// sun.misc.BASE64Decoder().decodeBuffer(message);
final byte[] plainText = decipher.doFinal(message);
return new String(plainText,"UTF-8");
}
用法:
byte[] codedtext = new Common().encrypt("HELLOWORLD!"); // Function to get the Encrption
输出:
base64: Ya9zBTukyOmdOh5/5vCaGA== // encrypted string converted to base64
Encrypted : [B@d41c149
解密:
String decodedtext = new Common().decrypt(codedtext); // To decrypt String
输出:
Decrypted : HELLOWORLD! // from Encrypted string
现在,如果我使用相同的 Key 和 String 在线获取加密密钥,我会得到不同的值。
Using this link 来验证我的加密/解密。
我刚刚开始加密/解密,因此对于我在这里做错的任何事情,任何帮助表示赞赏。
解决方法
你需要
final byte[] plainText = decipher.doFinal(Base64.getDecoder().decode(message));
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。