Python and java AES/ECB/PKCS5 encryption

2024/11/15 11:37:24

JAVA VERSION:

public class EncryptUtil {public static String AESEncode(String encodeRules, String content) {try {KeyGenerator keygen = KeyGenerator.getInstance("AES");keygen.init(128, new SecureRandom(encodeRules.getBytes()));SecretKey original_key = keygen.generateKey();byte[] raw = original_key.getEncoded();SecretKey key = new SecretKeySpec(raw, "AES");Cipher cipher = Cipher.getInstance("AES");cipher.init(Cipher.ENCRYPT_MODE, key);byte[] byte_encode = content.getBytes("utf-8");byte[] byte_AES = cipher.doFinal(byte_encode);return new String(Base64.getEncoder().encode(byte_AES));} catch (NoSuchAlgorithmException e) {e.printStackTrace();} catch (NoSuchPaddingException e) {e.printStackTrace();} catch (InvalidKeyException e) {e.printStackTrace();} catch (IllegalBlockSizeException e) {e.printStackTrace();} catch (BadPaddingException e) {e.printStackTrace();} catch (UnsupportedEncodingException e) {e.printStackTrace();}return null;}}

When i run this code:

System.out.println(EncryptUtil.AESEncode("1234567812345678", python&java"));

I've got:

V5FFUgDi7VZaJ0qGzDISoA==

PYTHON VERSION:

import base64from Crypto.Cipher import AESBLOCK_SIZE = 16  # Bytes
pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * \chr(BLOCK_SIZE - len(s) % BLOCK_SIZE)
unpad = lambda s: s[:-ord(s[len(s) - 1:])]class AESUtil:__BLOCK_SIZE_16 = BLOCK_SIZE_16 = AES.block_sizedef __init__(self, key):self.key = keydef encrypt(self, raw):raw = pad(raw)cipher = AES.new(self.key, AES.MODE_ECB)return base64.b64encode(cipher.encrypt(raw))def decrypt(self, enc):enc = base64.b64decode(enc)cipher = AES.new(self.key, AES.MODE_ECB)return unpad(cipher.decrypt(enc))

I know java use AES/ECB/PKCS#5 by default, but when I run the encrypt method :

cipher_text = AESUtil("1234567812345678").encryt('python&java')

got:b'3mjygpK1d7ThCRK98ssZhA=='

The pad and unpad i found them in Googles. How do I edit my PYTHON code make the cipher_text equals JAVA encryption. Can somebody know how to fix it?

Answer

You use different encryption keys

In Java

System.out.println(EncryptUtil.AESEncode("1234567812345678", "python&java"));

See the code:

KeyGenerator keygen = KeyGenerator.getInstance("AES");
keygen.init(128, new SecureRandom(encodeRules.getBytes()));
SecretKey original_key = keygen.generateKey();
byte[] raw = original_key.getEncoded();

If you print the raw key, you will get fd839759956ba4a47922e8ee7c902f52 (HEX encoded), that's the encryption key

If you would like to use the provided key directy, you should use

byte[] raw = encodeRules.getBytes(); 
// (assuming encodeRules has 16 bytes)

How do I edit my PYTHON code make the cipher_text equals JAVA encryption

That's tricky.. you may have a look how SecureRandom works, but IMHO it's easier to fix the Java implementation to create a key you expect

Regardless that I'd consider the implementation not secure enough - using ECB and simple key.

https://en.xdnf.cn/q/119669.html

Related Q&A

How to find the center point of this rectangle

I am trying to find the center point of the green rectangle which is behind the fish, but my approach is not working. Here is my code:#Finding contours (almost always finds those 2 retangles + some noi…

Simple Battleships game implementation in Python

Okay Im not sure how to develop another board with hidden spaces for the computers ships per-se, and have it test for hits. Again Im not even sure how Im going to test for hits on the board I have now.…

How to remove WindowsPath and parantheses from a string [duplicate]

This question already has an answer here:Reference - What does this regex mean?(1 answer)Closed 4 years ago.I need to remove WindowsPath( and some of the closing parentheses ) from a directory string.…

How to escape escape-characters

I have a string variable which is not printing properly, I guess because it contains escape characters. How to escape these escape-characters?>>> print "[p{Aa}\\P{InBasic_Latin}\r\t\n]&q…

Python Multiprocessing a large dataframe on Linux

As shown in the title, I have a big data frame (df) that needs to be processed row-wise, as df is big (6 GB), I want to utilize the multiprocessing package of python to speed it up, below is a toy exam…

How to pass more arguments through tkinter bind

How do I pass more arguments through tkinters bind method? for the example:tk = Tk() def moveShip(event,key):if event.keysym == Down and player1.selectedCoord[1] != 9:if key == place:player1.selectedC…

Python Class method definition : unexpected indent [duplicate]

This question already has answers here:Im getting an IndentationError (or a TabError). How do I fix it?(6 answers)Closed 6 months ago.I am getting started with Django and Python so naturally Im doing …

pandas python - round() not behaving correctly

Im rounding values in a dataframe to 1 decimal place. Here is the dfVren 2015 Hsten 2014 Vren 2014 Question 1) Maten r vllagad oc…

Converting dictionary into string

d={a:Apple,b:ball,c:cat}The above dictionary I have and I want my Output like the below-mentioned resultres="a=Apple,b=ball,c=cat"Is it possible in a pythonic way then please answer it I have…

Django Getting QuerySet.values() based on condition

Lets say I have a model Class Parent and a Class Child. And child has a field called status and a ForeignKey relationship to Parent.Lets say I retrieve one parent by calling filter (so as to have a Que…