对称加密算法(AES/ECB/PKCS5Padding)之ECB模式
2021-01-24 13:15
标签:pack hal row hello 解密 new cep nbsp encode package t1; import java.io.UnsupportedEncodingException; import javax.crypto.BadPaddingException; public class AES_ECB_Cipher { // 加密算法 // 加密 // 解密 public static void main(String[] args) throws UnsupportedEncodingException, InvalidKeyException, // 解密 } 输出结果 Message:Hello,world! encrypted using AES! 对称加密算法(AES/ECB/PKCS5Padding)之ECB模式 标签:pack hal row hello 解密 new cep nbsp encode 原文地址:https://www.cnblogs.com/dengw125792/p/12864826.html
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
static final String CIPHER_NAME = "AES/ECB/PKCS5Padding";
public static byte[] encrypt(byte[] key, byte[] input) throws NoSuchAlgorithmException, NoSuchPaddingException,
InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
Cipher cipher = Cipher.getInstance(CIPHER_NAME);
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");// byte[] key 转化为加密算饭AES的key
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);// 加密模式
return cipher.doFinal(input);
}
public static byte[] decrypt(byte[] key, byte[] input) throws NoSuchAlgorithmException, NoSuchPaddingException,
InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
Cipher cipher = Cipher.getInstance(CIPHER_NAME);
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
return cipher.doFinal(input);
}
NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
// 原文
String message = "Hello,world! encrypted using AES!";
byte[] data = message.getBytes(StandardCharsets.UTF_8);
System.out.println("Message:" + message);
// 128位密鈅=16bytes key:
byte[] key = "1234567890abcdef".getBytes("UTF-8");
// 加密
byte[] encrypted = encrypt(key, data);
System.out.println("Encrypted data:" + Base64.getEncoder().encodeToString(encrypted));// 转成BASE64
byte[] decrypted = decrypt(key, encrypted);
System.out.println("Decrypted data:" + new String(decrypted, "UTF-8"));
}
Encrypted data:wfZKKc4N88nFyYIcn0iEupAdmCzQbrUwdmJM6n6xyCiwe63g4KYhFxz5lyAJhErm
Decrypted data:Hello,world! encrypted using AES!
上一篇:Java面向对象
下一篇:C语言程序设计实验报告(6)
文章标题:对称加密算法(AES/ECB/PKCS5Padding)之ECB模式
文章链接:http://soscw.com/index.php/essay/46334.html