逆风行者刘 逆风行者刘
关注数: 22 粉丝数: 346 发帖数: 5,822 关注贴吧数: 23
有没有会python 也会java的,帮忙看看java的加密用python写的对 java代码 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
1 下一页