java的加密,试着用写python去写,不知这样对不对,有没有2者都通晓的大佬指点下
java(原文是2个文件的,而且各种乱,我算是重写了下,可能格式不太对):
import java.security.MessageDigest;
import java.security.spec.AlgorithmParameterSpec;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import android.util.Base64;
public final class AESCipher {
public static void main(String[] args) {
raw='texttext'
String cryptedStr = AESCipher.encrypt(raw);
System.out.println(cryptedStr);
public byte[] key() {
MessageDigest instance = MessageDigest.getInstance("SHA-256");
instance.update("AN2jH1M1FD9.UDN2".getBytes("UTF-8"));
Object key = new byte[32];
System.arraycopy(instance.digest(), 0, key, 0, 32);
return key;
public String encrypt(String raw) {
byte[] key=key();
byte[] iv=new byte[]{(byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0};
keyspec = new SecretKeySpec(key, "AES");
ivspec = new IvParameterSpec(iv);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
cipher.init((1, keyspec, ivspec);
byte[] encrypted = cipher.doFinal(raw.getBytes("UTF-8"));
String cryptedStr=new String(Base64.encode(encrypted ,0), "UTF-8");
return cryptedStr;
}
}
python:d
1
import hashlib
from Crypto.Cipher import AES
import base64
class AESCipher:
def __init__(self):
self.str_key='AN2jH1M1FD9.UDN2'
self.iv = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" # 16位字符,用来填充缺失内容,可固定值也可随机字符串,具体选择看需求。
def get_key(self):
instance=bytes(self.str_key, encoding="utf-8")
sha256 = hashlib.sha256()
sha256.update(instance)
key = sha256.digest()[:32]
return key
def __pad(self, text):
"""填充方式,加密内容必须为16字节的倍数,若不足则使用self.iv进行填充"""
text_length = len(text)
amount_to_pad = AES.block_size - (text_length % AES.block_size)
if amount_to_pad == 0:
amount_to_pad = AES.block_size
pad = chr(amount_to_pad)
return text + pad * amount_to_pad
def encrypt(self,raw):
key=self.get_key()
raw = self.__pad(raw) # 注意这里先将明文通过 utf-8 转码成为字节串再调用 padding 算法
cipher = AES.new(key, AES.MODE_CBC, self.iv, segment_size=128)# 注意这里 segment_size=128
encrypted = cipher.encrypt(raw)
cryptedStr = base64.b64encode(encrypted)
return cryptedStr