我有一个下面的 PHP 函数,我想在 Java 中实现但没有运气,我无法获得相同的输出:
function encryptText( $plainText, $key )
{
$mcopen = mcrypt_module_open (MCRYPT_TripleDES, "", MCRYPT_MODE_ECB,"");
$iv = mcrypt_create_iv (mcrypt_enc_get_iv_size ($mcopen), MCRYPT_RAND);
$td = mcrypt_module_open('tripledes', '', 'ecb', '');
$cryptedHash = '';
if (mcrypt_generic_init($td, $key, $iv) != -1)
{
$cryptedHash = mcrypt_generic($td, $plainText);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
}
return base64_encode($cryptedHash);
}
这是我在这里找到的java代码:
public static String encrypt(String message, String key) throws Exception {
final MessageDigest md = MessageDigest.getInstance("md5");
final byte[] digestOfPassword = md.digest(key.getBytes("utf-8"));
final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
for (int j = 0, k = 16; j < 8;) {
keyBytes[k++] = keyBytes[j++];
}
final SecretKey keyz = new SecretKeySpec(keyBytes, "DESede");
final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
final Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, keyz, iv);
final byte[] plainTextBytes = message.getBytes("utf-8");
final byte[] cipherText = cipher.doFinal(plainTextBytes);
final String encodedCipherText = new sun.misc.BASE64Encoder().encode(cipherText);
return encodedCipherText;
}