I am tasked with converting this java code to python. And I am unable to achieve the same result as java in python. I need help in converting this code. Any hints are greatly appreciated.
Java Code
import org.apache.commons.lang.RandomStringUtils;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import java.util.Base64;
public String decryptTextusingAES(String text, String kek) throws Exception{
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] keyBytes= new byte[16];
byte[] b= kek.getBytes("UTF-8");
int len= b.length;
if (len> keyBytes.length) len = keyBytes.length;
System.arraycopy(b, 0, keyBytes, 0, len);
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
IvParameterSpec ivSpec = new IvParameterSpec(keyBytes);
cipher.init(Cipher.DECRYPT_MODE,keySpec,ivSpec);
BASE64Decoder decoder = new BASE64Decoder();
byte [] results = cipher.doFinal(decoder.decodeBuffer(text));
return new String(results,"UTF-8");
}
Python Code
from Crypto.Cipher import AES
from base64 import b64decode
BLOCK_SIZE = AES.block_size
pad = lambda s: s + (BLOCK_SIZE - len(s.encode()) % BLOCK_SIZE) * chr(BLOCK_SIZE - len(s.encode()) % BLOCK_SIZE)
unpad = lambda s: s[:-ord(s[len(s) - 1:])]
class AESCipher:
def __init__(self, secretkey: str):
self.key = secretkey # key
self.iv = secretkey[0:16] # offset
def decrypt(self, encrypted_text):
encrypted_text = b64decode(encrypted_text)
cipher = AES.new(key=self.key.encode(), mode=AES.MODE_CBC, IV=self.iv.encode())
decrypted_text = cipher.decrypt(encrypted_text)
print("unpad : ",decrypted_text)
return unpad(decrypted_text).decode('utf-8')
if __name__ == '__main__':
# message to encrypt
message = "mxoqPaEdpujwTOmeKGomHgXAgdVc0Ca7cm0Qqjm2WMQ="
secret_key = "935554679694777871163316"
AES_pkcs5_obj = AESCipher(secret_key)
decrypted_message = AES_pkcs5_obj.decrypt(message)
print("Decrypted : ",decrypted_message)
Python Code keeps giving this output:
unpad : b'rt\xfb\x98o\x8f.\t\xb1d0tx-i\x88\xd1\xfdV\xef\xece\xf2\x8a\xf7\xf8\x00O\xdb\x8c\xcb\xf2'
Decrypted :
But it should give this in decrypted: 284174634921775587013963
This is encrpted string "mxoqPaEdpujwTOmeKGomHgXAgdVc0Ca7cm0Qqjm2WMQ="
This is the key that should be used "935554679694777871163316" to decrypt the above string.