current position:Home>Python encrypts and decrypts des to solve the problem of inconsistency with Java results

Python encrypts and decrypts des to solve the problem of inconsistency with Java results

2022-01-30 05:35:47 Random code 3000

Little knowledge , Great challenge ! This article is participating in “   A programmer must have a little knowledge   ” Creative activities

Python DES CBC Encryption and decryption code demonstration

import binascii
from pyDes import des, CBC, PAD_PKCS5


def des_encrypt(s):
    """ DES  encryption  :param s:  Original string  :return:  Encrypted string ,16 Base number  """
    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  Decrypt  :param s:  The encrypted string ,16 Base number  :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 code 

Perform the above Python Code , The output is as follows :

1dbbd4e9246ebffa
zx
 Copy 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 code 

Perform the above Java Code , Output :

 Before encryption :zx
 After encryption :1DBBD4E9246EBFFA
 After decryption :zx
 Copy code 

matters needing attention

python There is also a library in Crypto Also used for encryption , But the result of encryption and java atypism , It's a pit , Here are Crypto Encrypted code , For comparison :

from Crypto.Cipher import DES
import binascii
import base64

# data-> Encrypted string  key-> secret key   Also pass in the string 
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()  #  After decryption, the extra characters added during encryption '\0' Delete 




# data-> Encrypted string  key-> secret key   Also pass in the string 
def aes_encrypt(data, key):
    # DES CBC Pattern   Demand vector iv
    iv = key.encode()
    cipher = DES.new(key.encode(),iv, DES.MODE_CBC)
    #  String to byte array 
    b_data = data.encode()
    # ------  according to 16 Bit on its   Insufficient space  ----
    block_size = DES.block_size
    count = len(b_data)
    # text No 16 That will make up for 16 Multiple 
    add_count = block_size - (count % block_size)
    s_plaintext = data + (' ' * add_count)
    # ------  according to 16 Bit on its   Insufficient space  ----
  
    b_plaintext = s_plaintext.encode()
    encrypted = cipher.encrypt(b_plaintext)  # des encryption 

    return base64.b64encode(encrypted).decode()

 Copy code 

copyright notice
author[Random code 3000],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201300535449091.html

Random recommended