码迷,mamicode.com
首页 > 编程语言 > 详细

对称加密算法(AES/ECB/PKCS5Padding)之ECB模式

时间:2020-05-10 21:27:15      阅读:93      评论:0      收藏:0      [点我收藏+]

标签:pack   hal   row   hello   解密   new   cep   nbsp   encode   

package t1;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

public class AES_ECB_Cipher {

// 加密算法
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);
}

public static void main(String[] args) throws UnsupportedEncodingException, InvalidKeyException,
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"));
}

}

输出结果

Message:Hello,world! encrypted using AES!
Encrypted data:wfZKKc4N88nFyYIcn0iEupAdmCzQbrUwdmJM6n6xyCiwe63g4KYhFxz5lyAJhErm
Decrypted data: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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!