当前位置:网站首页>AES encryption CBC mode pkcs7padding filling Base64 encoding key 32byte iv16byte
AES encryption CBC mode pkcs7padding filling Base64 encoding key 32byte iv16byte
2022-07-02 21:01:00 【VincentlVL】
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;
import java.util.Arrays;
public class AES {
public static void main(String[] args) throws IOException {
AES aes = new AES();
// encryption secret key
// String key = "1234567890qwertyuiopasdfghjklzxc";
// b'\x87\xe9\x11\xfe\x82\xce\x8dS\x08;9\xd2\xbfx\x03\x95\x15\x99\xc2\x02\x9c\xcb\xaa\xd7G\x16\xd8\xae\x157U\xdb'
byte[] keybytes = {(byte)0x87,(byte)0xe9,(byte)0x11,(byte)0xfe,(byte)0x82,(byte)0xce,(byte)0x8d,'S',(byte)0x08,';','9',(byte)0xd2,(byte)0xbf,'x',(byte)0x03,(byte)0x95,(byte)0x15,(byte)0x99,(byte)0xc2,(byte)0x02,(byte)0x9c,(byte)0xcb,(byte)0xaa,(byte)0xd7,'G',(byte)0x16,(byte)0xd8,(byte)0xae,(byte)0x15,'7','U',(byte)0xdb};
// byte[] keybytes = { '1','2','3','4','5','6','7','8','9','0','q','w','e','r','t','y','u','i','o','p','a','s','d','f','g','h','j','k','l','z','x','c' };
// byte[] keybytes = key.getBytes();
byte[] iv = {(byte)0x87,(byte)0xe9,(byte)0x11,(byte)0xfe,(byte)0x82,(byte)0xce,(byte)0x8d,'S',(byte)0x08,';','9',(byte)0xd2,(byte)0xbf,'x',(byte)0x03,(byte)0x95};
// Encrypted string
String content = "Hello, Han - mei - mei ";
System.out.println(" Before encryption :" + content);
System.out.println(" Encryption key :" + new String(keybytes));
// Encryption method
String enc = aes.encrypt(content.getBytes(), keybytes,iv);
// String encode = new BASE64Encoder().encode(enc);
System.out.println(" Encrypted content :" + enc);
// System.out.println(" Encrypted content :" + new String(Hex.encode(enc)));
// Decryption method
// byte[] bytes = new BASE64Decoder().decodeBuffer(enc);
String dec = aes.decrypt(enc, keybytes,iv);
System.out.println(" Decrypted content :" + new String(dec));
}
/**
*
* @author ngh
*
* AES128 Algorithm
*
* CBC Pattern
*
* PKCS7Padding Fill mode
*
* CBC The pattern needs to add a parameter iv
*
* Be situated between java I won't support it PKCS7Padding, Only support PKCS5Padding however PKCS7Padding and PKCS5Padding There's no difference
* To be realized in java End use PKCS7Padding fill , Need to use bouncycastle Component to implement
*/
// The algorithm name
final String KEY_ALGORITHM = "AES";
// Encryption and decryption algorithm / Pattern / fill style
final String algorithmStr = "AES/CBC/PKCS7Padding";
//
private Key key;
private Cipher cipher;
boolean isInited = false;
// String ivs = "1234567890qwerty";
// byte[] iv = ivs.getBytes();
// byte[] iv = {'1','2','3','4','5','6','7','8','9','0', 'q', 'w', 'e', 'r', 't', 'y' };
public void init(byte[] keyBytes) {
// If you don't have enough keys 16 position , Then make up . This if The content in is very important
int base = 16;
if (keyBytes.length % base != 0) {
int groups = keyBytes.length / base + (keyBytes.length % base != 0 ? 1 : 0);
byte[] temp = new byte[groups * base];
Arrays.fill(temp, (byte) 0);
System.arraycopy(keyBytes, 0, temp, 0, keyBytes.length);
keyBytes = temp;
}
// initialization
Security.addProvider(new BouncyCastleProvider());
// Turn it into JAVA The key format of
key = new SecretKeySpec(keyBytes, KEY_ALGORITHM);
try {
// initialization cipher
cipher = Cipher.getInstance(algorithmStr, "BC");
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchProviderException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Encryption method
*
* @param content
* The string to encrypt
* @param keyBytes
* Encryption key
* @return
*/
public String encrypt(byte[] content, byte[] keyBytes,byte[] iv) {
byte[] encryptedText = null;
init(keyBytes);
System.out.println("IV:" + new String(iv));
try {
cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));
encryptedText = cipher.doFinal(content);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String encode = new BASE64Encoder().encode(encryptedText);
return encode;
}
/**
* Decryption method
*
*
* String to decrypt
* @param keyBytes
* decryption key
* @return
*/
public String decrypt(String enc, byte[] keyBytes,byte[] iv) throws IOException {
byte[] encryptedData = new BASE64Decoder().decodeBuffer(enc);
byte[] encryptedText = null;
init(keyBytes);
System.out.println("IV:" + new String(iv));
try {
cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
encryptedText = cipher.doFinal(encryptedData);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// String encode = new BASE64Encoder().encode(encryptedText);
String str = new String(encryptedText);
return str;
}
}
边栏推荐
- I want to ask you, where is a better place to open an account in Dongguan? Is it safe to open a mobile account?
- Research Report on the overall scale, major manufacturers, major regions, products and applications of micro hydraulic cylinders in the global market in 2022
- Google Earth engine (GEE) - Landsat 9 image full band image download (Beijing as an example)
- Spark source code compilation, cluster deployment and SBT development environment integration in idea
- Activation function - relu vs sigmoid
- qwb2018_ core kernel_ rop
- 股票开户要找谁?手机开户是安全么?
- 1005 spell it right (20 points) "PTA class a exercise"
- Who do you want to open a stock account? Is it safe to open a mobile account?
- 证券如何在线开户?手机开户是安全么?
猜你喜欢

I did a craniotomy experiment: talk about macromolecule coding theory and Lao Wang's fallacy from corpus callosum and frontal leukotomy

Cs5268 perfectly replaces ag9321mcq typec multi in one docking station solution

pytorch 模型保存的完整例子+pytorch 模型保存只保存可訓練參數嗎?是(+解决方案)

Properties of expectation and variance

Review of the latest 2022 research on "deep learning methods for industrial defect detection"

Data preparation for behavior scorecard modeling

kernel tty_ struct

Highly qualified SQL writing: compare lines. Don't ask why. Asking is highly qualified..
![[hands on deep learning]02 softmax regression](/img/47/eb67ec2c51f6bb7d6b2879b36e769d.jpg)
[hands on deep learning]02 softmax regression

Implementing yolox from scratch: dataset class
随机推荐
I drew a Gu ailing with characters!
How to realize the function of detecting browser type in Web System
Cron expression (seven subexpressions)
Sword finger offer (I) -- handwriting singleton mode
想请教一下,究竟有哪些劵商推荐?手机开户是安全么?
Redis sentinel cluster working principle and architecture deployment # yyds dry goods inventory #
Go language learning summary (5) -- Summary of go learning notes
The first of the classic quotations of correspondents is heartbreaking
Happy Lantern Festival! Tengyuanhu made you a bowl of hot dumplings!
2021 software security report: open source code, happiness and disaster depend on each other?
I did a craniotomy experiment: talk about macromolecule coding theory and Lao Wang's fallacy from corpus callosum and frontal leukotomy
How to open an account online? Is it safe to open a mobile account?
kernel_ uaf
rwctf2022_ QLaaS
Is it safe to buy funds on securities accounts? Where can I buy funds
Record the problems encountered by nodejs asynchronism
Research Report on the overall scale, major manufacturers, major regions, products and applications of outdoor vacuum circuit breakers in the global market in 2022
Who do you want to open a stock account? Is it safe to open a mobile account?
Basic concept of database, installation and configuration of database, basic use of MySQL, operation of database in the project
pytorch 模型保存的完整例子+pytorch 模型保存只保存可訓練參數嗎?是(+解决方案)