当前位置:网站首页>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 :
边栏推荐
- 证券如何在线开户?手机开户是安全么?
- mysql
- Basic concept of database, installation and configuration of database, basic use of MySQL, operation of database in the project
- 2021 v+ Quanzhen internet global innovation and Entrepreneurship Challenge, one of the top ten audio and video scene innovation and application pioneers
- Driverless learning (III): Kalman filter
- 6 pyspark Library
- An analysis of the past and present life of the meta universe
- [shutter] the shutter plug-in is used in the shutter project (shutter plug-in management platform | search shutter plug-in | install shutter plug-in | use shutter plug-in)
- Research Report on the overall scale, major manufacturers, major regions, products and application segmentation of sound quality head simulators in the global market in 2022
- I want to ask you, where is a better place to open an account in Dongguan? Is it safe to open a mobile account?
猜你喜欢

Jetson XAVIER NX上ResUnet-TensorRT8.2速度与显存记录表(后续不断补充)

Activation function - relu vs sigmoid

Investment strategy analysis of China's electronic information manufacturing industry and forecast report on the demand outlook of the 14th five year plan 2022-2028 Edition

After 65 days of closure and control of the epidemic, my home office experience sharing | community essay solicitation
![[fluent] dart technique (independent main function entry | nullable type determination | default value setting)](/img/cc/3e4ff5cb2237c0f2007c61db1c346d.jpg)
[fluent] dart technique (independent main function entry | nullable type determination | default value setting)

Interested parties add me for private chat

疫情封控65天,我的居家办公心得分享 | 社区征文

Why do I have a passion for process?

API documentation tool knife4j usage details

6 pyspark Library
随机推荐
Exemple complet d'enregistrement du modèle pytoch + enregistrement du modèle pytoch seuls les paramètres d'entraînement sont - ils enregistrés? Oui (+ Solution)
BitSet complement
[shutter] statefulwidget component (create statefulwidget component | materialapp component | scaffold component)
JS modularization
[error record] the command line creates an error pub get failed (server unavailable) -- attempting retry 1 in 1 second
[shutter] the shutter plug-in is used in the shutter project (shutter plug-in management platform | search shutter plug-in | install shutter plug-in | use shutter plug-in)
Is it safe to buy funds on securities accounts? Where can I buy funds
Is it safe to open an account for online stock speculation? I'm a novice, please guide me
[hands on deep learning]02 softmax regression
Share several map bed websites for everyone to share pictures
[internship] solve the problem of too long request parameters
Write the content into the picture with type or echo and view it with WinHex
Basic concept of database, installation and configuration of database, basic use of MySQL, operation of database in the project
Go language learning summary (5) -- Summary of go learning notes
mysql
想请教一下,究竟有哪些劵商推荐?手机开户是安全么?
Detailed upgrade process of AWS eks
Activation function - relu vs sigmoid
Research Report on the overall scale, major manufacturers, major regions, products and applications of swivel chair gas springs in the global market in 2022
Research Report on ranking analysis and investment strategic planning of RFID market competitiveness of China's industrial manufacturing 2022-2028 Edition