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
The sidebar is recommended
- Python collects and monitors system data -- psutil
- Python chat room (Tkinter writing interface, streaming, socket to realize private chat, group chat, check chat records, Mysql to store data)
- Learning this Python library can reduce at least 100 lines of code
- leetcode 67. Add Binary(python)
- Regular re parameter replacement of Python 3 interface automation test framework
- V. pandas based on Python
- Only 15 lines of code is needed for face detection! (using Python and openCV)
- [Python crawler Sao operation] you can crawl Sirius cinema movies without paying
- leetcode 69. Sqrt(x)(python)
- Teach you to read the source code of Cpython (I)
guess what you like
-
Snowball learning started in the fourth quarter of Python. One needs three meals. I have a new understanding of Python functional programming, process-oriented, object-oriented and functional
-
leetcode 88. Merge Sorted Array(python)
-
Don't you know more about a python library before the end of 2021?
-
Python crawler web page parsing artifact XPath quick start teaching!!!
-
Use Python and OpenCV to watermark the image
-
String and related methods of Python data type introduction
-
Heapq module of Python module
-
Introduction to beautiful soup of Python crawler weapon, detailed explanation, actual combat summary!!!
-
Event loop of Python collaboration series
-
Django docking pin login system
Random recommended
- [recalling the 1970s] using Python to repair the wonderful memories of parents' generation, black-and-white photos become color photos
- You used to know Python advanced
- Pyinstaller package Python project
- 2021 IEEE programming language rankings: Python tops the list!
- Implementation of Python automatic test control
- Python advanced: [Baidu translation reverse] graphic and video teaching!!!
- Do you know the fuzzy semantics in Python syntax?
- [Python from introduction to mastery] (XXVII) learn more about pilot!
- Playing excel office automation with Python
- Some applications of heapq module of Python module
- Python and go languages are so popular, which is more suitable for you?
- Python practical skills task segmentation
- Python simulated Login, numpy module, python simulated epidemic spread
- Python opencv contour discovery function based on image edge extraction
- Application of Hoff circle detection in Python opencv
- Python reptile test ox knife (I)
- Day 1: learn the Django framework of Python development
- django -- minio_ S3 file storage service
- [algorithm learning] 02.03 Delete intermediate nodes (Java / C / C + + / Python / go)
- Similarities and differences of five pandas combinatorial functions
- Learning in Python + opencv -- extracting corners
- Python beginner's eighth day ()
- Necessary knowledge of Python: take you to learn regular expressions from zero
- Get your girlfriend's chat records with Python and solve the paranoia with one move
- My new book "Python 3 web crawler development practice (Second Edition)" has been recommended by the father of Python!
- From zero to familiarity, it will take you to master the use of Python len() function
- Python type hint type annotation guide
- leetcode 108. Convert Sorted Array to Binary Search Tree(python)
- For the geometric transformation of Python OpenCV image, let's first talk about the extraordinary resize function
- leetcode 701. Insert into a Binary Search Tree (python)
- For another 3 days, I sorted out 80 Python datetime examples, which must be collected!
- Python crawler actual combat | using multithreading to crawl lol HD Wallpaper
- Complete a python game in 28 minutes, "customer service play over the president card"
- The universal Python praise machine (commonly known as the brushing machine) in the whole network. Do you want to know the principle? After reading this article, you can write one yourself
- How does Python compare file differences between two paths
- Common OS operations for Python
- [Python data structure series] linear table - explanation of knowledge points + code implementation
- How Python parses web pages using BS4
- How do Python Network requests pass parameters
- Python core programming - decorator