当前位置:网站首页>3DES (deSede) encryption CBC mode pkcs7padding filling Base64 encoding key 24byte iv8byte
3DES (deSede) encryption CBC mode pkcs7padding filling Base64 encoding key 24byte iv8byte
2022-07-02 21:01:00 【VincentlVL】
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
/**
* DESede Encrypt/Decrypt class
*/
public class DESede extends BaseMethod{
public static void main(String[] args) throws Exception {
DESede desede = new DESede();
// encryption secret key
// 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 = {(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};
byte[] ivbytes = {(byte)0x87,(byte)0xe9,(byte)0x11,(byte)0xfe,(byte)0x82,(byte)0xce,(byte)0x8d,'S'};
// Encrypted string
String content = "{\"Kcv\":\"123456\",\"IDc\":\"User1\",\"IDo\":\"DataOwner1\",\"IDv\":\"222\",\"TS4\":\"1564657964010\",\"lifetime4\":\"657964010\","
+ "\"AC\":{\"IDc\":\"User1\",\"permission\":{\"Folder_pdf\":{\"Folder_pdf\":[0,1,1,1]}," +
"\"Folder_txt\":{\"Folder_txt\":[0,1,0,0],\"xiaohua.txt\":[0,1,1]}}}}";
// String content = "Hello, Han - mei - mei ";
System.out.println(" Before encryption :" + content);
// String key = Base64.getEncoder().encodeToString(keybytes);
// System.out.println(" Encryption key :" + key);
System.out.println(" Encryption key :" + new String(keybytes));
// Encryption method
String enc = desede.encrypt(Method.DESEDE_CBC_PKCS7Padding, keybytes, ivbytes, content.getBytes());
// 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 = desede.decrypt(Method.DESEDE_CBC_PKCS7Padding,keybytes, Key.SIZE_192,ivbytes, enc.getBytes());
System.out.println(" Decrypted content :" + dec);
}
private static final int VECTOR_LEGHT = 8;
/**
* All supported methods
*/
public enum Method{
DESEDE ("DESEDE"),
DESEDE_CBC_NoPadding ("DESEDE/CBC/NoPadding"),
DESEDE_CBC_PKCS5Padding ("DESEDE/CBC/PKCS5Padding"),
DESEDE_CBC_PKCS7Padding ("DESEDE/CBC/PKCS7Padding"),
DESEDE_CBC_ISO10126Padding ("DESEDE/CBC/ISO10126Padding");
private final String method;
Method(String method) {
this.method = method;
}
public String getMethod() {
return method;
}
}
/**
* Keysize must be equal to 128 or 192 bits.
* Default Keysize equals 128 bits.
*/
public enum Key{
SIZE_128 (16),
SIZE_192 (24);
private final int size;
Key(int size) {
this.size = size;
}
}
/**
* Implementation of DESede encryption
*/
// public static String encrypt(Method method, byte[] key, Key keySize, byte[] vector, byte[] message) throws Exception{
public static String encrypt(Method method, byte[] key, byte[] vector, byte[] message) throws Exception{
// generate Key
// byte[] keyBytes = generateKey(key, keySize.size);
SecretKeySpec keySpec = new SecretKeySpec(key, method.getMethod());
// generate Initialization Vector
// byte[] keyBytesIv = generateVector(vector, VECTOR_LEGHT);
IvParameterSpec ivSpec = new IvParameterSpec(vector);
Cipher cipher = Cipher.getInstance(method.getMethod());
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
byte[] cipherText = cipher.doFinal(message);
String encodeCipertext = Base64.getEncoder().encodeToString(cipherText);
// System.out.println(encodeCipertext);
return encodeCipertext;
}
/**
* Implementation of DESede decryption
*/
public static String decrypt(Method method, byte[] key, Key keySize, byte[] vector, byte[] message) throws Exception{
// generate Key
byte[] keyBytes = generateKey(key, keySize.size);
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, method.getMethod());
// generate Initialization Vector
byte[] keyBytesIv = generateVector(vector, VECTOR_LEGHT);
IvParameterSpec ivSpec = new IvParameterSpec(keyBytesIv);
Cipher cipher = Cipher.getInstance(method.getMethod());
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
// byte[] cipherText = cipher.doFinal(Base64.decode(message, Base64.DEFAULT));
byte[] cipherText = cipher.doFinal(Base64.getDecoder().decode(message));
return new String(cipherText);
}
}
import java.io.UnsupportedEncodingException;
abstract class BaseMethod {
/**
* Method for creation of valid byte array from key
*/
static byte[] generateKey(byte[] key, int lenght) throws UnsupportedEncodingException {
byte[] keyBytes = new byte[lenght];
int len = key.length;
if (len > keyBytes.length) {
len = keyBytes.length;
}
System.arraycopy(key, 0, keyBytes, 0, len);
return keyBytes;
}
/**
* Method for creation of valid byte array from initialization vector
*/
static byte[] generateVector(byte[] vector, int lenght) throws UnsupportedEncodingException {
byte[] keyBytesIv = new byte[lenght];
int len = vector.length;
if (len > keyBytesIv.length) {
len = keyBytesIv.length;
}
System.arraycopy(vector, 0, keyBytesIv, 0, len);
return keyBytesIv;
}
/**
* This method contains a list of encryption methods, that do does not have a initialization vector
*/
public static boolean hasInitVector(String method){
// All ECB methods do not support initialization vector
if(method.contains("ECB")){
return false;
}
switch (method){
case "PBEWITHSHA1AND128BITRC4":
case "PBEWITHSHA1AND40BITRC4":
case "PBEWITHSHAAND128BITRC4":
case "PBEWITHSHAAND40BITRC4":
return false;
}
return true;
}
}
If something goes wrong :java.security.NoSuchAlgorithmException: Cannot find any provider supporting DESEDE/CBC/PKCS7Padding
Refer to the blog link below :
边栏推荐
- 想请教一下,我在东莞,到哪里开户比较好?手机开户是安全么?
- 1005 spell it right (20 points) "PTA class a exercise"
- Go cache of go cache series
- Select function
- Friends who firmly believe that human memory is stored in macromolecular substances, please take a look
- Happy Lantern Festival! Tengyuanhu made you a bowl of hot dumplings!
- [fluent] dart technique (independent main function entry | nullable type determination | default value setting)
- Research Report on the overall scale, major manufacturers, major regions, products and application segmentation of power management units in the global market in 2022
- Redis -- three special data types
- Roommate, a king of time, I took care of the C language structure memory alignment
猜你喜欢
[shutter] statefulwidget component (create statefulwidget component | materialapp component | scaffold component)
Go language learning summary (5) -- Summary of go learning notes
The first of the classic quotations of correspondents is heartbreaking
通信人的经典语录,第一条就扎心了……
Codeforces round 651 (Div. 2) (a thinking, B thinking, C game, D dichotomy, e thinking)
Complete example of pytorch model saving +does pytorch model saving only save trainable parameters? Yes (+ solution)
Share the easy-to-use fastadmin open source system - Installation
7. Build native development environment
Redis sentinel cluster working principle and architecture deployment # yyds dry goods inventory #
[error record] the command line creates an error pub get failed (server unavailable) -- attempting retry 1 in 1 second
随机推荐
Basic concept of database, installation and configuration of database, basic use of MySQL, operation of database in the project
Common authority query instructions in Oracle
JS modularization
Sweet talk generator, regular greeting email machine... Open source programmers pay too much for this Valentine's day
MySQL learning notes (Advanced)
Research Report on the overall scale, major manufacturers, major regions, products and application segmentation of signal distributors in the global market in 2022
SBT tutorial
[question brushing diary] classic questions of dynamic planning
After 65 days of closure and control of the epidemic, my home office experience sharing | community essay solicitation
JDBC | Chapter 4: transaction commit and rollback
Friends who firmly believe that human memory is stored in macromolecular substances, please take a look
Research Report on the overall scale, major manufacturers, major regions, products and applications of capacitive voltage transformers in the global market in 2022
Burp install license key not recognized
Implementing yolox from scratch: dataset class
After eight years of test experience and interview with 28K company, hematemesis sorted out high-frequency interview questions and answers
pytorch 模型保存的完整例子+pytorch 模型保存只保存可訓練參數嗎?是(+解决方案)
Why do I have a passion for process?
26 FPS video super-resolution model DAP! Output 720p Video Online
[internship] solve the problem of too long request parameters
The first of the classic quotations of correspondents is heartbreaking