实验 DES算法的实现
代码
package s1;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.SecureRandom;
import java.util.Base64;
public class DES {
private static final String ALGORITHM = "DES";
private static final String TRANSFORMATION = "DES/ECB/PKCS5Padding";
public static void main(String[] args) throws Exception {
String plainText = "Hello, world!";
SecretKey secretKey = generateRandomKey();
byte[] cipherText = encrypt(plainText.getBytes(), secretKey);
String encodedCipherText = Base64.getEncoder().encodeToString(cipherText);
System.out.println("密文:" + encodedCipherText);
byte[] decryptedText = decrypt(Base64.getDecoder().decode(encodedCipherText), secretKey);
System.out.println("解密后的明文:" + new String(decryptedText));
}
public static SecretKey generateRandomKey() throws Exception {
KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
SecureRandom secureRandom = new SecureRandom();
keyGenerator.init(secureRandom);
return keyGenerator.generateKey();
}
public static byte[] encrypt(byte[] data, SecretKey key) throws Exception {
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.ENCRYPT_MODE, key);
return cipher.doFinal(data);
}
public static byte[] decrypt(byte[] data, SecretKey key) throws Exception {
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.DECRYPT_MODE, key);
return cipher.doFinal(data);
}
}
结果
密文:JKakqXhz5BZ7wktQm/xNLA==
解密后的明文:Hello, world!