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) {
String raw = "texttext";
String cryptedStr = AESCipher.encrypt(raw);
System.out.println(cryptedStr);
}
public static Object 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 static String encrypt(String raw) {
Object 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};
SecretKeySpec keyspec = new SecretKeySpec((byte[]) key, "AES");
AlgorithmParameterSpec ivspec = new IvParameterSpec(iv);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
byte[] encrypted = cipher.doFinal(raw.getBytes("UTF-8"));
String cryptedStr=new String(Base64.encode(encrypted ,0), "UTF-8");
return cryptedStr;
}
}
python的,不知這樣對不對
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
uj5u.com熱心網友回復:
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/46704.html
上一篇:Python畫圖
