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

Posted dengw125792

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了对称加密算法(AES/ECB/PKCS5Padding)之ECB模式相关的知识,希望对你有一定的参考价值。

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模式的主要内容,如果未能解决你的问题,请参考以下文章

非对称加密算法-RSA算法

谁帮我介绍下加密对称算法?

1、对称加密算法

对称加密算法和非对称加密算法

非对称加密算法的主要算法

加密技术对称与非对称加密简介