当前位置:网站首页>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;
}
}
边栏推荐
- Google Earth engine (GEE) - Landsat 9 image full band image download (Beijing as an example)
- How can testers do without missing tests? Seven o'clock is enough
- MySQL learning notes (Advanced)
- Number of DP schemes
- Happy Lantern Festival! Tengyuanhu made you a bowl of hot dumplings!
- [real case] trap of program design - beware of large data
- JDBC | Chapter 4: transaction commit and rollback
- [871. Minimum refueling times]
- Postman interface test practice, these five questions you must know
- Send blessings on Lantern Festival | limited edition red envelope cover of audio and video is released!
猜你喜欢

5 environment construction spark on yarn

Common routines of compressed packets in CTF

Cs5268 perfectly replaces ag9321mcq typec multi in one docking station solution

ROS learning (10): ROS records multiple topic scripts

Research Report on ranking analysis and investment strategic planning of RFID market competitiveness of China's industrial manufacturing 2022-2028 Edition

Interested parties add me for private chat

Second hand housing data analysis and prediction system

Friends who firmly believe that human memory is stored in macromolecular substances, please take a look

Driverless learning (4): Bayesian filtering

kernel tty_ struct
随机推荐
How can testers do without missing tests? Seven o'clock is enough
Welfare | Hupu isux11 Anniversary Edition is limited to hand sale!
2021 software security report: open source code, happiness and disaster depend on each other?
想请教一下,究竟有哪些劵商推荐?手机开户是安全么?
[real case] trap of program design - beware of large data
Who do you want to open a stock account? Is it safe to open a mobile account?
Codeforces Round #771 (Div. 2)(A-C)
Redis sentinel cluster working principle and architecture deployment # yyds dry goods inventory #
Data preparation for behavior scorecard modeling
Research Report on the overall scale, major manufacturers, major regions, products and applications of hollow porcelain insulators in the global market in 2022
Sword finger offer (I) -- handwriting singleton mode
Sweet talk generator, regular greeting email machine... Open source programmers pay too much for this Valentine's day
疫情封控65天,我的居家办公心得分享 | 社区征文
[871. Minimum refueling times]
Research and Analysis on the current situation of China's clamping device market and forecast report on its development prospect
Function, function, efficiency, function, utility, efficacy
想请教一下,我在东莞,到哪里开户比较好?手机开户是安全么?
现在券商的优惠开户政策什么?实际上网上开户安全么?
Cs5268 perfectly replaces ag9321mcq typec multi in one docking station solution
Talk about macromolecule coding theory and Lao Wang's fallacy from the perspective of evolution theory