我正在尝试使用以下代码对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, 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 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 ToDecrypt:
String decodedtext = new Common().decrypt(codedtext); // To decrypt String输出:
Decrypted : HELLOWORLD! // from Encrypted string现在,如果我使用相同的密钥和字符串在线获取加密密钥,我会得到不同的值。
验证我的加密/解密的Using this link。
我刚刚开始学习加密/解密,所以对于我在这里做错的任何事情,我都很感激。
发布于 2021-07-17 22:36:37
你需要
final byte[] plainText = decipher.doFinal(Base64.getDecoder().decode(message));https://stackoverflow.com/questions/68420294
复制相似问题