請幫我加密全字符串「測試加密字符串」。 這裏只對16個字節進行加密。 以下是我用於md5加密和解密的代碼。 請幫我加密更多的字節。md5加密和解密java無法加密超過16bytes
import java.security.MessageDigest;
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class Md5Encryption
{
private static final String ALGORITHM = "md5";
private static final String DIGEST_STRING = "HG58YZ3CR9";
private static final String CHARSET_UTF_8 = "utf-8";
private static final String SECRET_KEY_ALGORITHM = "DESede";
private static final String TRANSFORMATION_PADDING = "DESede/CBC/PKCS5Padding";
/* Encryption Method */
public String encrypt(String message) throws Exception
{
final MessageDigest md = MessageDigest.getInstance(ALGORITHM);
final byte[] digestOfPassword = md.digest(DIGEST_STRING.getBytes(CHARSET_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, SECRET_KEY_ALGORITHM);
final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
final Cipher cipher = Cipher.getInstance(TRANSFORMATION_PADDING);
cipher.init(Cipher.ENCRYPT_MODE, key, iv);
final byte[] plainTextBytes = message.getBytes(CHARSET_UTF_8);
final byte[] cipherText = cipher.doFinal(plainTextBytes);
return new String(cipherText);
}
/* Decryption Method */
public String decrypt(String message) throws Exception {
final MessageDigest md = MessageDigest.getInstance(ALGORITHM);
final byte[] digestOfPassword = md.digest(DIGEST_STRING.getBytes(CHARSET_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, SECRET_KEY_ALGORITHM);
final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
final Cipher decipher = Cipher.getInstance(TRANSFORMATION_PADDING);
decipher.init(Cipher.DECRYPT_MODE, key, iv);
final byte[] plainText = decipher.update(message.getBytes());
return new String(plainText, CHARSET_UTF_8);
}
public static void main(String[] args) throws Exception {
String text = "TEST STRING TO ENCRYPT";
String codedtext = new Md5Encryption().encrypt(text);
// String codedtext = ".ªÉ…U$L§U`8ˉ?¦」›°„";
String decodedtext = new Md5Encryption().decrypt(codedtext);
System.out.println(codedtext); // this is a byte array, you'll just see a reference to an array
System.out.println(decodedtext); // This correctly shows "TEST STRING TO ENCRYPT"
}
}
MD5不是加密算法 - 它是一個(不安全)單程哈希算法。 – chrixm
MD5是一種哈希算法,不是加密,因此你也不能解密它。多年來它也被認爲是毫無意義的,因爲它太快地被打破。 –
它只是供內部使用......所以沒問題 – vimal