Last active
July 25, 2024 16:27
-
-
Save crazygit/79eaacccd84f08a692615d19d960de37 to your computer and use it in GitHub Desktop.
AES Python Android encrypt decrypt, more see: https://github.com/crazygit/AES-Encryption-Demo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
# | |
### Dependence ############### | |
# pip install pycryptodome | |
############################## | |
import base64 | |
import hashlib | |
from Crypto import Random | |
from Crypto.Cipher import AES | |
from Crypto.Util.Padding import pad, unpad | |
class AESCipher: | |
def __init__(self, key): | |
self.key = hashlib.sha256(key.encode()).digest() | |
# 加密和解密不能用同一个实例对象,因此每次使用都生成一个新的实例对象 | |
def get_cipher(self, iv): | |
return AES.new(self.key, AES.MODE_CBC, iv) | |
def encrypt(self, plain_text): | |
pad_plain_text = pad(plain_text.encode(), AES.block_size) | |
iv = Random.new().read(AES.block_size) | |
cipher = self.get_cipher(iv) | |
return base64.b64encode(iv + cipher.encrypt(pad_plain_text)).decode() | |
@staticmethod | |
def extract_iv_and_encrypted_text(encrypted_message): | |
encrypted_message = base64.b64decode(encrypted_message) | |
iv = encrypted_message[:AES.block_size] | |
encrypted_text = encrypted_message[AES.block_size:] | |
return iv, encrypted_text | |
def decrypt(self, encrypted_message): | |
iv, encrypted_text = self.__class__.extract_iv_and_encrypted_text(encrypted_message) | |
cipher = self.get_cipher(iv) | |
return unpad(cipher.decrypt(encrypted_text), AES.block_size).decode() | |
if __name__ == '__main__': | |
key = 'this is my key' | |
plain_message = 'Hello World' | |
android_encrypted_message = '/an3uS3LSBbbPqX2aF5TH26ZegTudDi9f0Whg8FzwbE=' | |
aes_cipher = AESCipher(key) | |
python_encrypted_message = aes_cipher.encrypt(plain_message) | |
print(f'Python encrypted Message: {python_encrypted_message}') | |
print(f'Android encrypted Message: {android_encrypted_message}') | |
assert plain_message == aes_cipher.decrypt(python_encrypted_message) | |
assert plain_message == aes_cipher.decrypt(android_encrypted_message) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.anroid.testaescipher; | |
import android.util.Base64; | |
import java.io.UnsupportedEncodingException; | |
import java.security.InvalidAlgorithmParameterException; | |
import java.security.InvalidKeyException; | |
import java.security.MessageDigest; | |
import java.security.NoSuchAlgorithmException; | |
import java.security.SecureRandom; | |
import java.util.Arrays; | |
import javax.crypto.BadPaddingException; | |
import javax.crypto.Cipher; | |
import javax.crypto.IllegalBlockSizeException; | |
import javax.crypto.NoSuchPaddingException; | |
import javax.crypto.spec.IvParameterSpec; | |
import javax.crypto.spec.SecretKeySpec; | |
public class AESCipher { | |
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 messageDigestAlgorithm = "SHA-256"; | |
private static final int ivSize = 16; | |
private static byte[] keyBytes; | |
private static AESCipher instance = null; | |
AESCipher(String key) { | |
try { | |
MessageDigest md = MessageDigest.getInstance(messageDigestAlgorithm); | |
md.update(key.getBytes(characterEncoding)); | |
keyBytes = md.digest(); | |
} catch (NoSuchAlgorithmException e) { | |
e.printStackTrace(); | |
} catch (UnsupportedEncodingException e) { | |
e.printStackTrace(); | |
} | |
} | |
public static AESCipher getInstance(String key) { | |
if (instance == null) { | |
instance = new AESCipher(key); | |
} | |
return instance; | |
} | |
public String encrypt_string(final String plainMessage) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException { | |
return Base64.encodeToString(encrypt(plainMessage.getBytes()), Base64.DEFAULT); | |
} | |
public String decrypt_string(final String encryptedMessage) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException { | |
byte[] encryptedBytes = decrypt(Base64.decode(encryptedMessage, Base64.DEFAULT)); | |
return new String(encryptedBytes); | |
} | |
public byte[] encrypt(byte[] plainMessage) | |
throws NoSuchAlgorithmException, | |
NoSuchPaddingException, | |
InvalidKeyException, | |
IllegalBlockSizeException, | |
BadPaddingException, InvalidAlgorithmParameterException { | |
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, aesEncryptionAlgorithm); | |
SecureRandom random = new SecureRandom(); | |
byte[] ivBytes = new byte[ivSize]; | |
random.nextBytes(ivBytes); | |
IvParameterSpec ivSpec = new IvParameterSpec(ivBytes); | |
Cipher cipher = Cipher.getInstance(cipherTransformation); | |
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec); | |
byte[] inputBytes = new byte[ivBytes.length + plainMessage.length]; | |
System.arraycopy(ivBytes, 0, inputBytes, 0, ivBytes.length); | |
System.arraycopy(plainMessage, 0, inputBytes, ivBytes.length, plainMessage.length); | |
return cipher.doFinal(inputBytes); | |
} | |
public byte[] decrypt(byte[] encryptMessage) | |
throws NoSuchAlgorithmException, | |
NoSuchPaddingException, | |
InvalidKeyException, | |
InvalidAlgorithmParameterException, | |
IllegalBlockSizeException, | |
BadPaddingException { | |
byte[] ivBytes = Arrays.copyOfRange(encryptMessage, 0, ivSize); | |
byte[] inputBytes = Arrays.copyOfRange(encryptMessage, ivSize, encryptMessage.length); | |
IvParameterSpec ivSpec = new IvParameterSpec(ivBytes); | |
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, aesEncryptionAlgorithm); | |
Cipher cipher = Cipher.getInstance(cipherTransformation); | |
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec); | |
return cipher.doFinal(inputBytes); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.anroid.testaescipher; | |
import android.os.Bundle; | |
import android.support.v7.app.AppCompatActivity; | |
import android.util.Log; | |
import java.io.IOException; | |
import java.security.InvalidAlgorithmParameterException; | |
import java.security.InvalidKeyException; | |
import java.security.NoSuchAlgorithmException; | |
import javax.crypto.BadPaddingException; | |
import javax.crypto.IllegalBlockSizeException; | |
import javax.crypto.NoSuchPaddingException; | |
public class MainActivity extends AppCompatActivity { | |
private static final String TAG = "MainActivity"; | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_main); | |
try { | |
String key = "this is my key"; | |
String plainMessage = "Hello World"; | |
AESCipher aesCipher = AESCipher.getInstance(key); | |
String pythonEncryptedMessage = "d19laxPfz8dc+2oJSLKx5byD18ET3wAs/gbZsXEGjmw="; | |
String androidEncryptedMessage = aesCipher.encrypt_string(plainMessage); | |
Log.d(TAG, "Android Encrypted Message: " + androidEncryptedMessage); | |
Log.d(TAG, "Python Encrypted Message: " + pythonEncryptedMessage); | |
String androidDecryptMessage = aesCipher.decrypt_string(androidEncryptedMessage); | |
String pythonDecryptMessage = aesCipher.decrypt_string(pythonEncryptedMessage); | |
Log.d(TAG, "Origin Plain String: " + plainMessage); | |
Log.d(TAG, "Android decrypt Message: " + androidDecryptMessage); | |
Log.d(TAG, "Python decrypt Message: " + pythonDecryptMessage); | |
} catch (InvalidKeyException e) { | |
e.printStackTrace(); | |
} catch (NoSuchAlgorithmException e) { | |
e.printStackTrace(); | |
} catch (NoSuchPaddingException e) { | |
e.printStackTrace(); | |
} catch (IllegalBlockSizeException e) { | |
e.printStackTrace(); | |
} catch (BadPaddingException e) { | |
e.printStackTrace(); | |
} catch (InvalidAlgorithmParameterException e) { | |
e.printStackTrace(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment