Encrypt and Decrypt by AES algorithm in both python and android

2024/10/13 17:18:24

I have python and android code for AES encryption. When I encrypt a text in android, it decrypt on python successfully but it can’t decrypt in android side. Do anyone have an idea?

Python code :

import base64
import hashlib
from Crypto import Random
from Crypto.Cipher import AESclass AESCipher:def __init__(self, key):self.bs = 16self.key = hashlib.sha256(key.encode()).digest()def encrypt(self, message):message = self._pad(message)iv = Random.new().read(AES.block_size)cipher = AES.new(self.key, AES.MODE_CBC, iv)return base64.b64encode(iv + cipher.encrypt(message)).decode('utf-8')def decrypt(self, enc):enc = base64.b64decode(enc)iv = enc[:AES.block_size]cipher = AES.new(self.key, AES.MODE_CBC, iv)return self._unpad(cipher.decrypt(enc[AES.block_size:])).decode('utf-8')def _pad(self, s):return s + (self.bs - len(s) % self.bs) * chr(self.bs - len(s) % self.bs)@staticmethoddef _unpad(s):return s[:-ord(s[len(s)-1:])]

Android Code:

import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;import java.security.SecureRandom;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.util.Arrays;import android.annotation.SuppressLint;
import android.location.Criteria;
import android.util.Base64;
import android.util.Log;@SuppressLint("NewApi")
public class Crypt {private static final String tag = Crypt.class.getSimpleName();private static final String characterEncoding = "UTF-8";
private static final String cipherTransformation = "AES/CBC/PKCS5Padding";
private static final String aesEncryptionAlgorithm = "AES";
private static final String key = "this is my key";
private static byte[] ivBytes = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
private static byte[] keyBytes;private static Crypt instance = null;Crypt()
{SecureRandom random = new SecureRandom();Crypt.ivBytes = new byte[16];random.nextBytes(Crypt.ivBytes); 
}public static Crypt getInstance() {if(instance == null){instance = new Crypt();}return instance;
}public String encrypt_string(final String plain) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, IOException
{return Base64.encodeToString(encrypt(plain.getBytes()), Base64.DEFAULT);
}public String decrypt_string(final String plain) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, ClassNotFoundException, IOException
{byte[] encryptedBytes = decrypt(Base64.decode(plain, 0));return Base64.encodeToString( encryptedBytes, Base64.DEFAULT);
}public   byte[] encrypt(   byte[] mes)throws NoSuchAlgorithmException,NoSuchPaddingException,InvalidKeyException,InvalidAlgorithmParameterException,IllegalBlockSizeException,BadPaddingException, IOException {keyBytes = key.getBytes("UTF-8");Log.d(tag,"Long KEY: "+keyBytes.length);MessageDigest md = MessageDigest.getInstance("SHA-256");md.update(keyBytes);keyBytes = md.digest();Log.d(tag,"Long KEY: "+keyBytes.length);AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);SecretKeySpec newKey = new SecretKeySpec(keyBytes, aesEncryptionAlgorithm);Cipher cipher = null;cipher = Cipher.getInstance(cipherTransformation);SecureRandom random = new SecureRandom();   Crypt.ivBytes = new byte[16];               random.nextBytes(Crypt.ivBytes);            cipher.init(Cipher.ENCRYPT_MODE, newKey, random);
//    cipher.init(Cipher.ENCRYPT_MODE, newKey, ivSpec);byte[] destination = new byte[ivBytes.length + mes.length];System.arraycopy(ivBytes, 0, destination, 0, ivBytes.length);System.arraycopy(mes, 0, destination, ivBytes.length, mes.length);return  cipher.doFinal(destination);}public   byte[] decrypt(   byte[] bytes)throws NoSuchAlgorithmException,NoSuchPaddingException,InvalidKeyException,InvalidAlgorithmParameterException,IllegalBlockSizeException,BadPaddingException, IOException, ClassNotFoundException {keyBytes = key.getBytes("UTF-8");Log.d(tag,"Long KEY: "+keyBytes.length);MessageDigest md = MessageDigest.getInstance("SHA-256");md.update(keyBytes);keyBytes = md.digest();Log.d(tag,"Long KEY: "+keyBytes.length);byte[] ivB = Arrays.copyOfRange(bytes,0,16);Log.d(tag, "IV: "+new String(ivB));byte[] codB = Arrays.copyOfRange(bytes,16,bytes.length);AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivB);SecretKeySpec newKey = new SecretKeySpec(keyBytes, aesEncryptionAlgorithm);Cipher cipher = Cipher.getInstance(cipherTransformation);cipher.init(Cipher.DECRYPT_MODE, newKey, ivSpec);byte[] res = cipher.doFinal(codB); return  res;}}

When I ran this code on android:

String str = "this is local test";
Log.i("myTag", "step1: " + str);
String a = aesCrypt.encrypt_string(str);
Log.i("myTag", "step2: " + a);
String b = aesCrypt.decrypt_string(a);
Log.i("myTag", "step3: " + b);

Then I got this answer:

step1: this is local test
step2: a0F8MhzkSpRlM+aM1MKzUdVCoXIE5y5hh4PRuwPfAhofKwLJjTUbBvmJzTsKJDqF
step3: dGhpcyBpcyBsb2NhbCB0ZXN0

Do anyone have idea why it happens ?

Answer

You're encoding the output after decryption.

public String decrypt_string(final String plain) throws ...
{byte[] encryptedBytes = decrypt(Base64.decode(plain, 0));return Base64.encodeToString( encryptedBytes, Base64.DEFAULT);//     ^--------------------| this 
}

If you only encrypt printable data then you can safely remove the Base64.encodeToString call from the above code. To return the correct type, you can do

return new String(encryptedBytes);
https://en.xdnf.cn/q/69506.html

Related Q&A

How to conditionally assign values to tensor [masking for loss function]?

I want to create a L2 loss function that ignores values (=> pixels) where the label has the value 0. The tensor batch[1] contains the labels while output is a tensor for the net output, both have a …

Assign Colors to Lines

I am trying to plot a variable number of lines in matplotlib where the X, Y data and colors are stored in numpy arrays, as shown below. Is there a way to pass an array of colors into the plot function,…

How to display multiple annotations in Seaborn Heatmap cells

I want seaborn heatmap to display multiple values in each cell of the heatmap. Here is a manual example of what I want to see, just to be clear:data = np.array([[0.000000,0.000000],[-0.231049,0.000000]…

ImportError: No module named lxml on Mac

I am having a problem running a Python script and it is showing this message:ImportError: No module named lxmlI suppose I have to install somewhat called lxml but I am really newbie to Python and I don…

Pandas Rolling window Spearman correlation

I want to calculate the Spearman and/or Pearson Correlation between two columns of a DataFrame, using a rolling window.I have tried df[corr] = df[col1].rolling(P).corr(df[col2]) (P is the window size)b…

Python string splitlines() removes certain Unicode control characters

I noticed that Pythons standard string method splitlines() actually removes some crucial Unicode control characters as well. Example>>> s1 = uasdf \n fdsa \x1d asdf >>> s1.splitlines(…

Get only HTML head Element with a Script or Tool

I am trying to get large amount of status information, which are encoded in websites, mainly inside the "< head >< /head >" element. I know I can use wget or curl or python to get…

Is it possible to restore corrupted “interned” bytes-objects

It is well known, that small bytes-objects are automatically "interned" by CPython (similar to the intern-function for strings). Correction: As explained by @abarnert it is more like the inte…

Wildcard namespaces in lxml

How to query using xpath ignoring the xml namespace? I am using python lxml library. I tried the solution from this question but doesnt seem to work.In [151]: e.find("./*[local-name()=Buckets]&qu…

WordNet - What does n and the number represent?

My question is related to WordNet Interface.>>> wn.synsets(cat)[Synset(cat.n.01), Synset(guy.n.01), Synset(cat.n.03),Synset(kat.n.01), Synset(cat-o-nine-tails.n.01), Synset(caterpillar.n.02), …