Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”
Python DES CBC encryption and decryption code demonstration
import binascii
from pyDes import des, CBC, PAD_PKCS5
def des_encrypt(s) :
DES encrypted :param s: original string :return: encrypted string, hexadecimal ""
secret_key = '20171117'
iv = secret_key
k = des(secret_key, CBC, iv, pad=None, padmode=PAD_PKCS5)
en = k.encrypt(s, padmode=PAD_PKCS5)
return binascii.b2a_hex(en)
def des_descrypt(s) :
DES decryption :param s: encrypted string, hexadecimal :return: decrypted string """
secret_key = '20171117'
iv = secret_key
k = des(secret_key, CBC, iv, pad=None, padmode=PAD_PKCS5)
de = k.decrypt(binascii.a2b_hex(s), padmode=PAD_PKCS5)
return de
str_en = des_encrypt('zx')
print(str_en)
str_de = des_descrypt(str_en)
print(str_de)
Copy the code
Execute the Python code above and get the following output:
1dbbd4e9246ebffa
zx
Copy the code
Java DES CBC encryption and decryption code demonstration
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
public class Main {
public static void main(String[] args) {
String content="zx";
String key = "20171117";
System.out.println("Before encryption:" + content);
byte[] encrypted = DES_CBC_Encrypt(content.getBytes(), key.getBytes());
System.out.println("After encryption:" + byteToHexString(encrypted));
byte[] decrypted = DES_CBC_Decrypt(encrypted, key.getBytes());
System.out.println("After decryption:" + new String(decrypted));
}
public static byte[] DES_CBC_Encrypt(byte[] content, byte[] keyBytes) {
try {
DESKeySpec keySpec = new DESKeySpec(keyBytes);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey key = keyFactory.generateSecret(keySpec);
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(keySpec.getKey()));
byte[] result = cipher.doFinal(content);
return result;
} catch (Exception e) {
System.out.println("exception:" + e.toString());
}
return null;
}
private static byte[] DES_CBC_Decrypt(byte[] content, byte[] keyBytes) {
try {
DESKeySpec keySpec = new DESKeySpec(keyBytes);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey key = keyFactory.generateSecret(keySpec);
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(keyBytes));
byte[] result = cipher.doFinal(content);
return result;
} catch (Exception e) {
System.out.println("exception:" + e.toString());
}
return null;
}
private static String byteToHexString(byte[] bytes) {
StringBuffer sb = new StringBuffer(bytes.length);
String sTemp;
for (int i = 0; i < bytes.length; i++) {
sTemp = Integer.toHexString(0xFF & bytes[i]);
if (sTemp.length() < 2)
sb.append(0);
sb.append(sTemp.toUpperCase());
}
return sb.toString();
}
}
Copy the code
Execute the Java code above and output:
Before encryption: zx After encryption: 1DBBD4E9246EBFFA After decryption: zxCopy the code
Matters needing attention
There is also a library in Python, Crypto, which is also used for encryption, but the result of encryption is not the same as that of Java. This is a pit.
From Crypto.Cipher import DES import binascii import base64 # data-> key-> def des_decode(data, key): b_data = base64.b64decode(data) iv = key.encode() cipher = DES.new(key.encode(), iv,DES.MODE_CBC) decrypted = cipher.decrypt(b_data) decrypted.rstrip(b' ') return decrypted.decode() # # data-> encrypted string key-> def aes_encrypt(data, key): Cipher = DES. New (key.encode(),iv, Des.mode_cbc) # string to byte array b_data = data.encode() # ------ according to the 16 bits of its insufficiency space ---- block_size = des.block_size count = Len (b_data) # text = multiples of 16 add_count = block_size - (count % block_size) s_plaintext = data + (" * add_count) ---- b_plaintext = s_plaintext.encode() encrypted = cipher.encrypt(b_plaintext) # des encrypted return base64.b64encode(encrypted).decode()Copy the code