行者刘6 2020-05-14 01:55 采纳率: 0%
浏览 324

java的AES/CBC/PKCS7(5)Padding加密算法,如何用python写?

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

  • 写回答

1条回答 默认 最新

  • 关注
    评论

报告相同问题?

悬赏问题

  • ¥50 关于在matlab上对曲柄摇杆机构上一点的运动学仿真
  • ¥15 jetson nano
  • ¥15 :app:debugCompileClasspath'.
  • ¥15 windows c++内嵌qt出现数据转换问题。
  • ¥20 公众号如何实现点击超链接后自动发送文字
  • ¥15 用php隐藏类名和增加类名
  • ¥15 算法设计与分析课程的提问
  • ¥15 用MATLAB汇总拟合图
  • ¥15 智能除草机器人方案设计
  • ¥15 对接wps协作接口实现消息发送