Last active
October 12, 2020 12:23
-
-
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 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 pycrypto==2.6.1 | |
############################## | |
import base64 | |
import hashlib | |
from Crypto import Random | |
from Crypto.Cipher import AES | |
class AESCipher: | |
bs = AES.block_size | |
def __init__(self, key): | |
self.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) | |
@staticmethod | |
def _unpad(s): | |
return s[:-ord(s[len(s) - 1:])] | |
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 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 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