python java 互通的RSA 加密方式PKCS8EncodedKeySpec

java代碼

package ex20;

import jdk.internal.org.objectweb.asm.tree.TryCatchBlockNode;

import java.lang.reflect.Field;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;



public  class CodecUtil {

    public static void main(String args[])throws Exception {


        String generateSortedContent = "{\"endSettleDay\":\"2019-01-01\",\"page\":1,\"shopId\":\"1248896\",\"size\":10,\"startSettleDay\":\"2019-01-01\"}";
        String sign = CodecUtil.MD5.encodeToString(generateSortedContent);
        System.out.println(sign);
        String meituan_APPSECRET = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAI0iW4k0Sf0g4YTdbIbELOfgi7pisd6zPcn/C2oxlRx2pxDEFljNEz6QjzIY4wCY0YONa8+qlmA7OVWrjl961YnBijhWVOw+Rn51Dwbt3hvWqi3alSGXhpiwp/MyuJd8M6bqz9G2kV0CHY54SeF5qufPLPiGML56UALvVMI7nE9dAgMBAAECgYAWIa4i/N0hYZebwzEyjO7Rycd/idyEpKzq0SDUHURZu02FdopekIIVDIw3+ekW/d/U9kdSwFhmbMMX6RghZty3SIiuGeHsSb6d8vThDUf8ihH04M/UJfQ8JcGrizkFycj0hDUs1okMrNMhYmxxKqCH0LyEg3YvncfaYKSp7f1OgQJBAPqDjO+52pDeyxpUMNXwKuWpxkJxiSG8nKSP3XBo/ZlTLow0/WMFAZG4y7arGn8shDtodeTtE7P7NspFoGCKlf0CQQCQOZg7Ix+JHRPw6p0LrDurg+fi83huZ/YRra/a26tz3AD4ziryFAljfryW+oft+LX/a5msFS7fjam7UK5bUyzhAkBJX1xZHmtIwShllsES+BvoVlhuP4i1q+OJQ2XNNcMJNFbO0/pfFSlHgAOShfzlwKkeKVNWcKWzsmFyzv/RJuYVAkA+tTwSYmggxsrX0jqsS5u6LGUTkYbIgl1EPH+cqix2+K5Xf9S+YqXeY8l937pgZuZDAzbS0ncJ7l9hOWhF/vkhAkAUX1UE4kRa/G4Ok8pfkOPi3X66ai/pV5jm4I+4kayW4N4mJKylQ08FXFt5vBAYEcNuxcf1mwL2zuH4uzCOByTB";
        String str = RSA.publicEncrypt(sign,meituan_APPSECRET);
        System.out.println(str);
    }

    private CodecUtil() {
    }

    public static class RSA {

        private static final String ALGORITHM = "RSA";
        private static final String DEFAULT_CHARSET = "UTF-8";
        private static KeyPairGenerator keyPairGen = null;
        private static KeyFactory keyFactory = null;
        private static Cipher cipher = null;

        private static ConcurrentHashMap<String, PublicKey> publicKeyMap = new ConcurrentHashMap<>();

        static{
            try {
                init();
            } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {

            }
        }
        private static synchronized void init() throws NoSuchAlgorithmException, NoSuchPaddingException {
            keyPairGen = KeyPairGenerator.getInstance(ALGORITHM);
            keyPairGen.initialize(1024);
            keyFactory = KeyFactory.getInstance(ALGORITHM);
            cipher = Cipher.getInstance(ALGORITHM);
        }

        public static KeyPair generateKeyPair() throws Exception {
            if (null == keyPairGen) {
                synchronized (RSA.class) {
                    if (null == keyPairGen) {
                        init();
                    }
                }
            }
            return keyPairGen.generateKeyPair();
        }

        public static String getPublicKeyStr(KeyPair pair) {
            PublicKey publicKey = pair.getPublic();
            String publicKeyStr = CodecUtil.encodeToStringByBase64(publicKey.getEncoded());
            return publicKeyStr;
        }

        public static String getPrivateKeyStr(KeyPair pair) {
            PrivateKey privateKey = pair.getPrivate();
            String privateKeyStr = CodecUtil.encodeToStringByBase64(privateKey.getEncoded());
            return privateKeyStr;
        }

        public static String publicDecrypt(String str, String publicKeyStr) throws Exception {

            if (cipher == null) {

            }
            PublicKey pubKey = publicKeyMap.computeIfAbsent(publicKeyStr, (k)->{
                byte[] decoded = CodecUtil.decodeByBase64(publicKeyStr);
                try {
                    return keyFactory.generatePublic(new X509EncodedKeySpec(decoded));
                } catch (InvalidKeySpecException e) {

                    return null;
                }
            });

            if (null == pubKey) {

            }

            // RSA解密
            cipher.init(Cipher.DECRYPT_MODE, pubKey);
            // 64位解碼加密後的字符串
            byte[] inputByte = CodecUtil.decodeByBase64(str.getBytes(DEFAULT_CHARSET));
            String outStr = new String(cipher.doFinal(inputByte));
            return outStr;
        }

        public static String publicEncrypt(String str, String privateKey) throws Exception {
            if (cipher == null) {
                //LOG.error("CodecUtil.RSA初始化失敗,cipher爲null, ALGORITHM 不存在, ALGORITHM is " + ALGORITHM);
                //throw new CodecException("CodecUtil.RSA初始化失敗,cipher爲null, ALGORITHM 不存在, ALGORITHM is " + ALGORITHM);
            }
            // base64編碼的公鑰
            byte[] decoded = CodecUtil.decodeByBase64(privateKey);
            RSAPrivateKey priKey = (RSAPrivateKey) keyFactory.generatePrivate(new PKCS8EncodedKeySpec(decoded));
            // RSA加密
            cipher.init(Cipher.ENCRYPT_MODE, priKey);
            return CodecUtil.encodeToStringByBase64(cipher.doFinal(str.getBytes(DEFAULT_CHARSET)));
        }

        public static String privateSign(String privateKeyStr, Object obj) throws Exception {
            String generateSortedContent = generateSortedContent(obj);
            String sign = CodecUtil.MD5.encodeToString(generateSortedContent);



            return publicEncrypt(sign, privateKeyStr);
        }


    }


    public static class MD5 extends HashEncoder {

        private static final String ALGORITHM = "MD5";

        public static String encodeToString(String str) throws Exception {
            //System.out.println(str);
            return encodeToString(ALGORITHM, str);
        }

        public static byte[] encode(String str) throws Exception {
            return encode(ALGORITHM, str);
        }
    }

    public static class HashEncoder {
        protected static String encodeToString(String algorithm, String str) throws Exception {
            //System.out.println(algorithm);
            return encodeToStringByBase64(encode(algorithm, str));
        }

        protected static byte[] encode(String algorithm, String str) throws Exception {
            if (str == null || algorithm == null) {
                return null;
            }
            MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
            messageDigest.update(str.getBytes());
            return messageDigest.digest();
        }
    }

    public static String encodeToStringByBase64(byte[] bytes) {
        return Base64.getEncoder().encodeToString(bytes);
    }

    public static byte[] encodeByBase64(byte[] bytes) {
        return Base64.getEncoder().encode(bytes);
    }

    public static byte[] decodeByBase64(String str) {
        return Base64.getDecoder().decode(str);
    }

    public static byte[] decodeByBase64(byte[] bytes) {
        return Base64.getDecoder().decode(bytes);
    }

    public static String generateSortedContent (Object obj) {
        TreeMap<String, Object> paramMap = new TreeMap<>();
        try {
            Class<? extends Object> classz = obj.getClass();
            do {
                Field[] declaredFields = classz.getDeclaredFields();
                for (Field field : declaredFields) {
                    String fieldName = field.getName();
                    if (fieldName.equals("serialVersionUID")) {
                        continue;
                    }
                    field.setAccessible(true);
                    paramMap.put(fieldName, field.get(obj));
                }
                classz = classz.getSuperclass();
            } while (!classz.equals(Object.class));
        } catch (Exception e) {
            return null;
        }
        return null;
    }

}

python代碼


import json
import requests
import hashlib

import base64
import M2Crypto
import textwrap


def MD5(str):
    return base64.b64encode(hashlib.md5(str.encode('utf-8')).digest())


def private_encrypt(data, private_key):
    private_key = '''-----BEGIN PRIVATE KEY-----
{0}
-----END PRIVATE KEY-----'''.format('\n'.join(textwrap.wrap(private_key, width=64)))
    bio = M2Crypto.BIO.MemoryBuffer(private_key)
    rsa_pri = M2Crypto.RSA.load_key_bio(bio)
    ctxt_pri = rsa_pri.private_encrypt(data, M2Crypto.RSA.pkcs1_padding)
    ctxt64_pri = ctxt_pri.encode('base64').replace("\n", "")
    return ctxt64_pri```

 - List item

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章