当前位置:网站首页>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 :
边栏推荐
- Check the confession items of 6 yyds
- 【QT】QPushButton创建
- Properties of expectation and variance
- [hands on deep learning]02 softmax regression
- 在券商账户上买基金安全吗?哪里可以买基金
- Research Report on the overall scale, major manufacturers, major regions, products and applications of metal oxide arresters in the global market in 2022
- Analyze comp-206 advanced UNIX utils
- 股票开户要找谁?手机开户是安全么?
- [871. Minimum refueling times]
- After eight years of test experience and interview with 28K company, hematemesis sorted out high-frequency interview questions and answers
猜你喜欢

rwctf2022_ QLaaS

Complete example of pytorch model saving +does pytorch model saving only save trainable parameters? Yes (+ solution)

In depth research and investment feasibility report of global and Chinese isolator industry, 2022-2028

Share the easy-to-use fastadmin open source system - Installation

Interested parties add me for private chat

Summary of interview experience, escort your offer, full of knowledge points

Check the confession items of 6 yyds

Common routines of compressed packets in CTF

After 65 days of closure and control of the epidemic, my home office experience sharing | community essay solicitation

API documentation tool knife4j usage details
随机推荐
Record the problems encountered by nodejs asynchronism
Import a large amount of data to redis in shell mode
rwctf2022_ QLaaS
[fluent] dart function (function composition | private function | anonymous function | function summary)
1007 maximum subsequence sum (25 points) "PTA class a exercise"
[12] the water of the waves is clear, which can wash my tassel. The water of the waves is muddy, which can wash my feet
Number of DP schemes
Don't you want to have a face-to-face communication with cloud native and open source experts? (including benefits
Research Report on the overall scale, major manufacturers, major regions, products and application segmentation of signal distributors in the global market in 2022
pytorch 模型保存的完整例子+pytorch 模型保存只保存可训练参数吗?是(+解决方案)
[question brushing diary] classic questions of dynamic planning
Check the confession items of 6 yyds
[real case] trap of program design - beware of large data
In depth research and investment feasibility report on the global and China active vibration isolation market 2022-2028
What is online account opening? Is it safe to open an account online now?
[hands on deep learning]02 softmax regression
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
在网上炒股开户安全吗?我是新手,还请指导
[fluent] dart technique (independent main function entry | nullable type determination | default value setting)