美文网首页
RSA加解密、签名、AES加密 python、java版本

RSA加解密、签名、AES加密 python、java版本

作者: woniuxia | 来源:发表于2020-04-24 16:48 被阅读0次

    说明

    • python、java 双向验证RSA、加解密、签名
    • 支持RSA 1024、2048加解密
    • python、java AES双向加解密

    参考

    java代码--AES

    package encrypt;
    
    import cn.hutool.core.codec.Base64;
    import com.sun.istack.internal.NotNull;
    
    import javax.crypto.Cipher;
    import javax.crypto.spec.SecretKeySpec;
    import java.util.Random;
    
    public class AESUtils {
        private static String cipherMode = "AES/ECB/PKCS5Padding";//算法/模式/补码方式
    
        /*   AES秘钥支持128bit/192bit/256bit三种长度的秘钥,一个字节等于8bit,
         *   因此支持生成的字符串的长度应该是 16/24/32
         * */
        private static int keyLength = 24;
    
    
        public static void main(String[] args) {
    
            /*构建一个随机密码*/
            String key = getRandomKey(keyLength);
            System.out.println("随机生成的key:" + key);
    
            String data = "1234567890111111111111111111111111";
    
            try {
                String encriptData = AESUtils.encrypt(data, key);
                System.out.println("加密后的数据:" + encriptData);
    
                String decryptData = decrypt(encriptData, key);
    
                System.out.println("解密后的数据:" + decryptData);
    
            } catch (Exception e) {
                e.printStackTrace();
            }
    
        }
    
    
        /**
         * @param length 需要生成的字符串长度
         * @return 随机生成的字符串
         */
        public static String getRandomKey(int length) {
    
            if (length != 16 && length != 24 && length != 32) {
                System.out.println("长度必须为16/24/32");
                return null;
            }
    
            String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            Random random = new Random();
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < length; i++) {
                int number = random.nextInt(62);
                stringBuilder.append(str.charAt(number));
            }
            return stringBuilder.toString();
    
        }
    
    
        /**
         * @param data 需要加密的数据
         * @param key  加密使用的key
         * @return 加密后的数据(Base64编码)
         * @throws Exception
         */
        public static String encrypt(String data, @NotNull String key) throws Exception {
    
            int length = key.length();
            if (length != 16 && length != 24 && length != 32) {
                System.out.println("长度必须为16/24/32");
                return null;
            }
    
            byte[] raw = key.getBytes("utf-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance(cipherMode);
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            byte[] encrypted = cipher.doFinal(data.getBytes("utf-8"));
    
            return Base64.encode(encrypted);
        }
    
    
        /**
         * @param data 需要解密的数据
         * @param key  解密用的key
         * @return 解密后的数据
         * @throws Exception
         */
        public static String decrypt(String data, @NotNull String key) throws Exception {
            try {
                int length = key.length();
                if (length != 16 && length != 24 && length != 32) {
                    System.out.println("长度必须为16/24/32");
                    return null;
                }
    
                byte[] raw = key.getBytes("utf-8");
                SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
                Cipher cipher = Cipher.getInstance(cipherMode);
                cipher.init(Cipher.DECRYPT_MODE, skeySpec);
                byte[] encrypted = Base64.decode(data);//先用base64解密
                try {
                    byte[] original = cipher.doFinal(encrypted);
                    return new String(original, "utf-8");
                } catch (Exception e) {
                    System.out.println(e.toString());
                    return null;
                }
            } catch (Exception ex) {
                System.out.println(ex.toString());
                return null;
            }
        }
    
    }
    
    
    

    java代码--RSA

    package encrypt;
    
    import cn.hutool.core.codec.Base64;
    
    import javax.crypto.Cipher;
    import java.io.ByteArrayOutputStream;
    import java.security.*;
    import java.security.interfaces.RSAPrivateKey;
    import java.security.interfaces.RSAPublicKey;
    import java.security.spec.PKCS8EncodedKeySpec;
    import java.security.spec.X509EncodedKeySpec;
    import java.util.HashMap;
    import java.util.Map;
    
    public class RSAUtils {
    
        /**
         * 加密算法RSA
         */
        private static final String KEY_ALGORITHM = "RSA";
    
        /**
         * 签名算法
         */
        private static final String SIGNATURE_ALGORITHM = "SHA256withRSA";
    
        /**
         * 获取公钥的key
         */
        private static final String PUBLIC_KEY = "RSAPublicKey";
    
    
        /**
         * 获取私钥的key
         */
        private static final String PRIVATE_KEY = "RSAPrivateKey";
    
    
        /**
         * RSA最大加密明文大小
         */
        private static final int MAX_ENCRYPT_BLOCK = 117;
    
    
        /**
         * RSA最大解密密文大小
         */
        private static final int MAX_DECRYPT_BLOCK = 256;
    
    
        public static void main(String[] args) {
    
    
            /*RSA  1024 */
    //        String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCIarYvrIMZGHKa8f2E6ubg0//28R1zJ4ArD+XELXYvDrM8UBR42PqJCpjPN3hC91YAnnk2Y9U+X5o/rGxH5ZTZzYy+rkAmZFJa1fK2mWDxPYJoxH+DGHQc+h8t83BMB4pKqVPhcJVF6Ie+qpD5RFUU/e5iEz8ZZFDroVE3ubKaKwIDAQAB";
    //        String privateKey = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAIhqti+sgxkYcprx/YTq5uDT//bxHXMngCsP5cQtdi8OszxQFHjY+okKmM83eEL3VgCeeTZj1T5fmj+sbEfllNnNjL6uQCZkUlrV8raZYPE9gmjEf4MYdBz6Hy3zcEwHikqpU+FwlUXoh76qkPlEVRT97mITPxlkUOuhUTe5sporAgMBAAECgYA0aSND37iifKUTaKOpXIKFoI23910EMAnrAXmaTIkafUBZjL7Ay0Q+QIcDHeGjgNlW9YvGXMbB5wMhMYKMgOUV1FpeqQdDslO4Z7zynRjkDJkjOKkE2/j10CvmNO8e2uCWKsYYUE9IyTkxcypjBCv16ifT0qmdxb7uKLccYI16eQJBANMutfNO/q7kUKiYvilBLN9+pZOg6eTmKmV0Xygoa3ClpQTfurwLA8W/Fv3oXnjHXTryNVHeoxSH69imo0RZ9kcCQQClXhMbXlfvl5iInmwziFhtYBztvkLuyQ084FgszR7iR0nuOWoURLQa5O7sLL724FNRlSvOCmmmWguh2vmQgRr9AkBDS5tHkWCvMqpRT3spgk9eWOlChgCCpKXV9qNsFJVILEDNsM28pnXpSd91wdp4+m7HHe/Hyv6EyFtrio50dYZ5AkAODVVwUO8GBArJKTUml+JzwOQUa8OCSQFf9+xmOjPypH4qySQzfrcTRfrrhM3haqSJ3TQwuP/LTAGLCnGEjwP9AkBqFFyrrQviPOhwel3NWjRv8mftOFgnm0Isk/NQJ4JtoahYvPDeUyP80WSuVWnPyV4zHz9Kw7BggYCPc4xZDACV";
    
    
            /*RSA 2048*/
            String publicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAichGTEP0QFswnvn+ZAQrgGHM8VeDZLJuezGhgxh4d9SyRUfnIW/zefT71rwS4bZUs1MPxJwavOyxABJOHLuckdHXknCsGEWz78gsA6D0+O+9dl1gCZR29nnN/NlzmNbSjFnzvsTJYBlS88qSr35RXFE+6DM7uPsS8Fm2I+65FteJ8p2yMvpSg72QkIX8xvI1F1uwXrciIB+4u7uTozxIplMOo4a6uhAm3W+Kjpz3ni2btjGqHRbqb3ebSZyl+nFfnjQaBe3XyVxAWDSanjgFj/wbqbeug9FBs+nQFVPIZR9z0aE5Ndi5o3eSkV7HFmWpkxaiPZ0BLRK3XHMaBtuSpwIDAQAB";
            String privateKey = "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCJyEZMQ/RAWzCe+f5kBCuAYczxV4Nksm57MaGDGHh31LJFR+chb/N59PvWvBLhtlSzUw/EnBq87LEAEk4cu5yR0deScKwYRbPvyCwDoPT47712XWAJlHb2ec382XOY1tKMWfO+xMlgGVLzypKvflFcUT7oMzu4+xLwWbYj7rkW14nynbIy+lKDvZCQhfzG8jUXW7BetyIgH7i7u5OjPEimUw6jhrq6ECbdb4qOnPeeLZu2MaodFupvd5tJnKX6cV+eNBoF7dfJXEBYNJqeOAWP/Bupt66D0UGz6dAVU8hlH3PRoTk12Lmjd5KRXscWZamTFqI9nQEtErdccxoG25KnAgMBAAECggEBAIPz1b88ZTMtIgdejA7lH3Q4Nbn8gc1yRPSet3uBd/3rKT/IeMZBHQBzaqxgOgUIRV3n8nXsun6sf2b+IOjLlErimH2agnZMauL85YokH/g4QU6WZl9GXBf41xmMd3SsZ8AadaEBfYoXNqZcHtcLNogfFwvx5QRn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VyWE0uCLFPW2JoNalX1WHlRuytblc2c+fpM5dKa4O65fTwCXfrvZldAFxvYoZVSKs3XTr6M8djoSpog+XyK7xEmp7mZj8/mG6n1x21y9TZzdKVGavSIE2bDxr03ZoLwzZ1tPHQ9zvGr/pspPq307vxsM0f5PB19fXmAlQ4PPeU7qno3xU2CaTVc+GGtwU5JNsRVCbm+ODoTL92P79nLWSFV9y93W3hmZMu1ozAPh8rOZZtGe+Wly1r7Y8cb8XnmgoF4NZmROkb3WAIhUA1AXdbzZAK4y+88INczHsUpIZVeJyX4JAWuNeARJtRWsMxDP7AL+HsWDgrtBw==";
            try {
    
    //            String data = "测试提交数据";
                String data = "h6mZVXRkr6fODpNs0BkaO0ZD";
    
                byte[] publicEncryptBytes = RSAUtils.encryptByPublicKey(data.getBytes(), publicKey);
                System.out.println("公钥加密后的数据:" + Base64.encode(publicEncryptBytes));
                byte[] privatDecryptBytes = RSAUtils.decryptByPrivateKey(publicEncryptBytes, privateKey);
                System.out.println("私钥解密后的数据:" + new String(privatDecryptBytes));
    //            byte[] privatDecryptBytes2 = RSAUtils.decryptByPrivateKey(Base64.decode(testData), privateKey);
    //            System.out.println("python加密java私钥解密后的数据:" + new String(privatDecryptBytes2));
    
                System.out.println("--------------------");
    
                byte[] privateKeyEncryptBytes = RSAUtils.encryptByPrivateKey(data.getBytes(), privateKey);
                System.out.println("私钥加密后的数据:" + Base64.encode(privateKeyEncryptBytes));
    
                String singnData = RSAUtils.sign(data.getBytes(), privateKey);
                System.out.println("私钥签名后的数据:" + singnData);
    
    
                byte[] publicDecryptBytes = RSAUtils.decryptByPublicKey(privateKeyEncryptBytes, publicKey);
                System.out.println("公钥解密后的数据:" + new String(publicDecryptBytes));
    
                boolean isSign = RSAUtils.verify(data.getBytes(), publicKey, singnData);
                System.out.println("签名是否正确:" + isSign);
    
                Map<String, Object> key = genKeyPair(1024);
                System.out.println("生成密钥:" + key.toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
    
        /**
         * @param keySize 生成的秘钥长度  一般为1024或2048
         * @return
         * @throws Exception
         */
        public static Map<String, Object> genKeyPair(int keySize) throws Exception {
            KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
            keyPairGen.initialize(keySize);
            KeyPair keyPair = keyPairGen.generateKeyPair();
            RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
            RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
            Map<String, Object> keyMap = new HashMap<String, Object>(2);
            keyMap.put(PUBLIC_KEY, publicKey);
            keyMap.put(PRIVATE_KEY, privateKey);
    
            System.out.println("publicKey:" + Base64.encode(publicKey.getEncoded()));
            System.out.println("privateKey:" + Base64.encode(privateKey.getEncoded()));
    
            return keyMap;
        }
    
    
        /**
         * 对已加密数据进行签名
         *
         * @param data       已加密的数据
         * @param privateKey 私钥
         * @return 对已加密数据生成的签名
         * @throws Exception
         */
    
        public static String sign(byte[] data, String privateKey) throws Exception {
            byte[] keyBytes = Base64.decode(privateKey);
            PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
            Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
            signature.initSign(privateK);
            signature.update(data);
            return Base64.encode(signature.sign());
        }
    
    
        /**
         * 验签
         *
         * @param data      签名之前的数据
         * @param publicKey 公钥
         * @param sign      签名之后的数据
         * @return 验签是否成功
         * @throws Exception
         */
        public static boolean verify(byte[] data, String publicKey, String sign) throws Exception {
            byte[] keyBytes = Base64.decode(publicKey);
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            PublicKey publicK = keyFactory.generatePublic(keySpec);
            Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
            signature.initVerify(publicK);
            signature.update(data);
            return signature.verify(Base64.decode(sign));
        }
    
    
        /**
         * 用私钥对数据进行解密
         *
         * @param encryptedData 使用公钥加密过的数据
         * @param privateKey    私钥
         * @return 解密后的数据
         * @throws Exception
         */
        public static byte[] decryptByPrivateKey(byte[] encryptedData, String privateKey) throws Exception {
            byte[] keyBytes = Base64.decode(privateKey);
            PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
            //Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, privateK);
    
            int inputLen = encryptedData.length;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            int offSet = 0;
            byte[] cache;
            int i = 0;
            // 对数据分段解密
            while (inputLen - offSet > 0) {
                if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
                    cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
                } else {
                    cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
                }
                out.write(cache, 0, cache.length);
                i++;
                offSet = i * MAX_DECRYPT_BLOCK;
            }
            byte[] decryptedData = out.toByteArray();
            out.close();
    
    
            return decryptedData;
        }
    
        /**
         * 公钥解密
         *
         * @param encryptedData 使用私钥加密过的数据
         * @param publicKey     公钥
         * @return 解密后的数据
         * @throws Exception
         */
        public static byte[] decryptByPublicKey(byte[] encryptedData, String publicKey) throws Exception {
            byte[] keyBytes = Base64.decode(publicKey);
            X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            Key publicK = keyFactory.generatePublic(x509KeySpec);
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.DECRYPT_MODE, publicK);
            int inputLen = encryptedData.length;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            int offSet = 0;
            byte[] cache;
            int i = 0;
            // 对数据分段解密
            while (inputLen - offSet > 0) {
                if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
                    cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
                } else {
                    cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
                }
                out.write(cache, 0, cache.length);
                i++;
                offSet = i * MAX_DECRYPT_BLOCK;
            }
            byte[] decryptedData = out.toByteArray();
            out.close();
            return decryptedData;
        }
    
    
        /**
         * 公钥加密
         *
         * @param data      需要加密的数据
         * @param publicKey 公钥
         * @return 使用公钥加密后的数据
         * @throws Exception
         */
        public static byte[] encryptByPublicKey(byte[] data, String publicKey) throws Exception {
            byte[] keyBytes = Base64.decode(publicKey);
            X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            Key publicK = keyFactory.generatePublic(x509KeySpec);
            // 对数据加密
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.ENCRYPT_MODE, publicK);
            int inputLen = data.length;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            int offSet = 0;
            byte[] cache;
            int i = 0;
            // 对数据分段加密
            while (inputLen - offSet > 0) {
                if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
                    cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
                } else {
                    cache = cipher.doFinal(data, offSet, inputLen - offSet);
                }
                out.write(cache, 0, cache.length);
                i++;
                offSet = i * MAX_ENCRYPT_BLOCK;
            }
            byte[] encryptedData = out.toByteArray();
            out.close();
            return encryptedData;
        }
    
    
        /**
         * 私钥加密
         *
         * @param data       待加密的数据
         * @param privateKey 私钥
         * @return 使用私钥加密后的数据
         * @throws Exception
         */
        public static byte[] encryptByPrivateKey(byte[] data, String privateKey) throws Exception {
            byte[] keyBytes = Base64.decode(privateKey);
            PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.ENCRYPT_MODE, privateK);
            int inputLen = data.length;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            int offSet = 0;
            byte[] cache;
            int i = 0;
            // 对数据分段加密
            while (inputLen - offSet > 0) {
                if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
                    cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
                } else {
                    cache = cipher.doFinal(data, offSet, inputLen - offSet);
                }
                out.write(cache, 0, cache.length);
                i++;
                offSet = i * MAX_ENCRYPT_BLOCK;
            }
            byte[] encryptedData = out.toByteArray();
            out.close();
            return encryptedData;
        }
    
    
        /**
         * 获取私钥
         *
         * @param keyMap 生成的秘钥对
         * @return
         * @throws Exception
         */
        public static String getPrivateKey(Map<String, Object> keyMap) throws Exception {
            Key key = (Key) keyMap.get(PRIVATE_KEY);
            return Base64.encode(key.getEncoded());
        }
    
    
        /**
         * 获取公钥
         *
         * @param keyMap 生成的秘钥对
         * @return
         * @throws Exception
         */
        public static String getPublicKey(Map<String, Object> keyMap) throws Exception {
            Key key = (Key) keyMap.get(PUBLIC_KEY);
            return Base64.encode(key.getEncoded());
        }
    }
    
    

    python 版本代码

    # -*- coding:utf-8 -*-
    """
    File Name: CryptUtils
    Author: wabi
    Data: 2020/4/16 13:49
    -----------------------
    Info:
        java、python验证版本
        SHA256withRSA 签名
        RSA2 公钥加密
        RSA2 私钥解密
        AES 加密、解密
        AES 密钥生成
    -----------------------
    Change Activity:
        2020/4/16: create
    """
    import base64
    import binascii
    import logging
    
    from Crypto.Random import get_random_bytes
    from Crypto.Signature import pkcs1_15, PKCS1_v1_5 as PKCS1_v1_5_sign
    from Crypto.Util.Padding import pad, unpad
    from Crypto import Random
    from Crypto.Cipher import AES, PKCS1_OAEP, PKCS1_v1_5
    from Crypto.PublicKey import RSA
    from Crypto.Hash import SHA, SHA256
    from urllib.parse import unquote
    
    from app.comm.encrypt import fill_public_key_marker, fill_private_key_marker
    
    logger = logging.getLogger(__file__)
    
    
    class CryptUtils(object):
    
        @staticmethod
        def get_sign_data(data: dict):
            """
            获取签名数据
            按照ASCII 字母排序 键值
            {'a':1,'b':2} => 'a=1&b=1'
            @param data:
            @return:
            """
            sort_param = sorted(
                [(key, value) for key, value in data.items() if key not in ['sign', 'sign_type']])
            return "&".join("{}={}".format(k, v) for k, v in sort_param)
    
        @staticmethod
        def gen_aes_key(length):
            """
            生成AES随机密钥
            @return:
            """
            b_key = get_random_bytes(length)
            return binascii.hexlify(b_key).decode('utf-8')
    
        @staticmethod
        def aes_en(data, aes_key):
            """
            AES加密
            @param data:
            @param aes_key:
            @return:
            """
            cipher = AES.new(aes_key.encode('utf-8'), AES.MODE_ECB)
            ct = cipher.encrypt(pad(data.encode('utf-8'), AES.block_size))
            return base64.b64encode(ct).decode('utf-8')
    
        @staticmethod
        def aes_de(data, aes_key):
            """
            AES解密
            @param data:
            @param aes_key:
            @return:
            """
            cipher = AES.new(aes_key.encode('utf-8'), AES.MODE_ECB)
            d_str = cipher.decrypt(base64.b64decode(data.encode('utf-8')))
            return unpad(d_str, AES.block_size).decode('utf-8')
    
        @staticmethod
        def rsa_pkcs_1_v_15_pub_en(data, rsa_key_pub):
            """
            rsa 公钥加密
            @param data:
            @param rsa_key_pub:
            @return:
            """
            public_key = fill_public_key_marker(rsa_key_pub)
            public_key_obj = RSA.import_key(public_key)
            cipher_rsa = PKCS1_v1_5.new(public_key_obj)
            enc_data = cipher_rsa.encrypt(data.encode('utf-8'))
            return base64.b64encode(enc_data).decode('utf-8')
    
        @staticmethod
        def rsa_pkcs_1_v_15_pri_de(data, rsa_key_pri):
            """
            RSA 私钥解密
            @param data:    密文
            @param rsa_key_pri: 私钥
            @return:
            """
            private_key = fill_private_key_marker(rsa_key_pri)
            private_key_obj = RSA.import_key(private_key)
            cipher_rsa = PKCS1_v1_5.new(private_key_obj)
            dsize = SHA.digest_size
            sentinel = Random.new().read(15 + dsize)
            dec_data = cipher_rsa.decrypt(base64.b64decode(data), sentinel)
            return dec_data.decode('utf-8')
    
        @staticmethod
        def gen_rsa_sign(data, rsa_key_pri):
            """
            rsa 签名
            @param data:
            @param rsa_key_pri:
            @return:
            """
            private_key = fill_private_key_marker(rsa_key_pri)
            private_key_obj = RSA.import_key(private_key)
            msg_hash = SHA256.new(data.encode())
            signature = PKCS1_v1_5_sign.new(private_key_obj).sign(msg_hash)
            sign = base64.b64encode(signature).decode()
            return sign
    
        @staticmethod
        def verify_sign(data, sign, rsa_pub_cus):
            """
            SHA256withRSA 验签
            @param data:
            @param sign:
            @param rsa_pub_cus:
            @return:
            """
            public_key = fill_public_key_marker(rsa_pub_cus)
            public_key_obj = RSA.import_key(public_key)
            msg_hash = SHA256.new(data.encode())
            try:
                PKCS1_v1_5_sign.new(public_key_obj).verify(msg_hash, base64.b64decode(unquote(sign)))
                return True
            except (ValueError, TypeError):
                return False
    
    
    # aes_obj = CryptUtils()
    # print(aes_obj.get_sign_data({'a': 1, 'b': 2, 'a1': 3}))
    # print(aes_obj.gen_aes_key(16))
    # aes_key = '5010f29d2834c931b26f10ad5720b108'
    # en_data = aes_obj.aes_en('1234567890111111111111111111111111', aes_key)
    # print(en_data)
    # # # en_data = 'rQUuELRSfJz5CrsmGrPObg=='
    # print(aes_obj.aes_de(en_data, aes_key))
    
    # publicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAichGTEP0QFswnvn+ZAQrgGHM8VeDZLJuezGhgxh4d9SyRUfnIW/zefT71rwS4bZUs1MPxJwavOyxABJOHLuckdHXknCsGEWz78gsA6D0+O+9dl1gCZR29nnN/NlzmNbSjFnzvsTJYBlS88qSr35RXFE+6DM7uPsS8Fm2I+65FteJ8p2yMvp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AI02smSn3lXYok1VBS3sCgYEApXEZS6gjUu4o7ZL53Ur1HDfi/nxpkxqrPh+D1HVYjzjT+4vTeZwtLXt2VCInPWNXH+f11mzhxIrLkI0jMcSCah81DuU8aFXnqvPuyFvt9uaQBYlVWBtkcGZyeaxHFrbfCyeu0jm7SfwmiIg12hKlIHtPTjEZQUX+kkWr8cdaZ8UCgYEAh0Pl+K09QzVc97yC0jmeTnTnlYWvksvdnKUw3nZvYtSukndH75nLhfr524HOs+5xwnUDd+3hCjaJDSEd7yf5lUfmr+1XdoXNTb0igrfxU/JLWbfU4geuqnaaDyACTxHmfLePC4C413ZJ61fxaCDvjsrN+JgTZanGt0EcRT3WC3kCgYEAgf5/GMJxlw0JXbs515a5R8Xl9358Whj/at3KcRsPTeIiNqnkrc54dR9ol60KViMDZ0+VDDobn5pLXzZ26/jzXD1PLHgU4gp18Q6glhAdx/3cNm11gLhtUCA/XLlwVjm0wggZRpgUQIr/IBKe9c3mr8IUS2Uq6e38nKRf+adhst0CgYAM4tvl+U1MPbbz3YzDv8QPepZ7Pglgdfxqfr5OkXA7jNhqTZjSq10B6oClGvirBo1m6f26F02iUKk1n67AuiLlTP/RRZHi1cfq6P9IaXl23PcxJfUMvIxQDS0U+UTFpNXryTw/qNAkSfufN48YzKdGvc8vHrYJyaeemaVlbdJOCw=="
    #
    # test_data = '测试提交数据'
    
    # ed_data = aes_obj.rsa_en(test_data, publicKey)
    # ed_data2 = aes_obj.rsa_pkcs_1_v_15_en(test_data, publicKey)
    # print('公钥加密数据:' + ed_data)
    # print('公钥加密数据ed_data2:' + ed_data2)
    # print('私钥解密数据:' + aes_obj.rsa_de(ed_data, privateKey))
    #
    # # 测试java加密后密文
    # java_en_data = 'ZtqovikGmPL34HK/6SSj148y5wmJRISka04FkL+jrwRHsCpuVOhG/UTrnPItwdvO6G2J9tmY/KN1rtX1F6wIQ5Tx/gysaCk3agKXHjaJYF/wBN/WSUV6vqlvKbfY9H4LJqa6nJGyax0hQ7tvctXwgJ3Pr5pcYbTExrTdJwHlxQXraHH7SzwA8UNwfi1nTMkrPzg6giY1iACVEmyiuTl4MdP609RT8DWxlPwpj7HdZx6V0F9yMigRSx/DQd3/62gxcq+1MafIjr0gdPMUtKHw/cvRvoun5kDJbSI4D1pH9EsLM7UX/gTocpmmBpbLYQaUKY/d2duQ5QXuSlj/ZB2B4g=='
    # print('java加密后python私钥解密数据:' + aes_obj.rsa_pkcs_1_v_15_de(java_en_data, privateKey))
    #
    
    # print('签名验证.....')
    # sign = aes_obj.gen_rsa_sign(test_data, privateKey)
    # print('python生成签名:' + sign)
    # print('验证签名结果:' + str(aes_obj.verify_sign(test_data, sign, publicKey)))
    
    

    相关文章

      网友评论

          本文标题:RSA加解密、签名、AES加密 python、java版本

          本文链接:https://www.haomeiwen.com/subject/yrgfwhtx.html