将AES加密java转换为Python

时间:2018-03-25 15:39:05

标签: java python encryption aes

我有使用AES加密的Java代码,我想转换它以便它在python中工作。这是一个主类,我创建了initVector常量,因此更容易看出它是否有效:

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.*;
import java.io.BufferedWriter;



public class test {
public static void main(String [] args)
{
    String ss = "pUypiz-7hJ0y_JtpKWaydp";
    String url = "";
    String toBeEncrypted = "";
    String initVector = "IqtY8jgALtjZNLM5";
    String encodedInitVector = Encryptor.encodeB64mod(initVector.getBytes());
    toBeEncrypted = "ch21979714702=put";
    ss = Encryptor.decodeB64Mod(ss);
    url = "i=" + encodedInitVector + "\n&a=" + Encryptor.encrypt(initVector, ss, toBeEncrypted);
    System.out.println(url);
}
}

这是Encryptor类:

import android.util.Base64;
import java.util.Random;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.io.IOUtils;
import java.util.*;

public class Encryptor {

public static String encrypt(String initVector, String key, String clearText) {
    try {
        byte[] value = clearText.getBytes("UTF-8");
        IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
        SecretKeySpec skeySpec = new SecretKeySpec(Base64.decode(key, 0), "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
        cipher.init(1, skeySpec, iv);
        return encodeB64mod(cipher.doFinal(value));
    } catch (Exception ex) {
        ex.printStackTrace();
        return "";
    }
}

public static String encodeB64mod(byte[] bytes) {
    return Base64.encodeToString(bytes, 2).replace('+', '-').replace(IOUtils.DIR_SEPARATOR_UNIX, '_').replace("=", "");
}



}

我试图让它在python中工作,但我做错了

编辑:

import base64
from Crypto.Cipher import AES
from Crypto import Random
raw ='ch21979714702=put'.encode('utf-8')
key = 'pUypiz-7hJ0y_JtpKWaydp' #should be conveted to hex
iv = b'IqtY8jgALtjZNLM5'
cipher = AES.new( key, AES.MODE_CBC, iv )
print (base64.b64encode( cipher.encrypt( raw ) ).decode('utf-8') )

2 个答案:

答案 0 :(得分:1)

您需要base64url解码,这不是通用的base 64编码:它将+替换为-,将/替换为_。这就是在Java中执行反向替换的原因。

Here是解码它的正确方法。请对进行投票,并将任何不包含替换字符最终填充的答案与=字符一起投票。

答案 1 :(得分:0)

Python中的问题是你需要使用填充

from Crypto.Util import Padding Padding.pad(raw, 16, style='pkcs7')

https://www.pycryptodome.org/en/latest/src/util/util.html

与Python中的java不同,您需要添加要使用填充的内容。