java和PHP 的非对称加密RSA/ECB/PKCS1Padding和对称加密DESede/ECB/PKCS5Padding;

  • Post author:
  • Post category:java


非对称加解密PHP

        /**
     * @desc Rsa加密
     *
     * @param $str
     * @param $public_key
     * @return bool|string
     * @author Tao
     * @email  804633234@qq.com
     * @date 2022-08-12 16:56
     */
    public function EnRsa($str,$public_key){
        //公钥加密
        $public_key = chunk_split($public_key , 64, "\n");
        $public_key = "-----BEGIN PUBLIC KEY-----\n$public_key-----END PUBLIC KEY-----\n";
        $key = openssl_pkey_get_public($public_key);
        if (!$key) {
            return('公钥不可用');
        }
        $result='';
        $data = str_split($str, 117);
        foreach ($data as $block) {
            openssl_public_encrypt($block, $dataEncrypt, $public_key, OPENSSL_PKCS1_PADDING);
            $result .= $dataEncrypt;
        }
        return  $result ? base64_encode($result) : null;
    }

    /**
     * @desc Rsa解密
     *
     * @param $str
     * @param $public_key
     * @return string
     * @author Tao
     * @email  804633234@qq.com
     * @date 2022-08-12 16:57
     */
    public function DeRsa($str,$private_key){
        $private_key = chunk_split($private_key , 64, "\n");
        $private_key = "-----BEGIN PRIVATE KEY-----\n".wordwrap($private_key)."-----END PRIVATE KEY-----";
        $private_key = openssl_pkey_get_private($private_key);
        if (!$private_key) {
            return('私钥不可用');
        }
        $crypto = '';
        foreach (str_split(base64_decode($str), 128) as $chunk) {
            openssl_private_decrypt($chunk, $decryptData, $private_key, OPENSSL_PKCS1_PADDING);
            $crypto .= $decryptData;
        }
        return $crypto;
    }

对称加解密PHP

     * @desc 对称加密
     *
     * @param $str
     * @return string
     * @author Tao
     * @email  804633234@qq.com
     * @date 2022-08-13 11:16
     */
    public function EnRsaEcb($str){
        return base64_encode(openssl_encrypt($str, 'DES-EDE3', $this->DESede, OPENSSL_RAW_DATA));
    }

    /**
     * @desc 对称解密
     *
     * @param $str
     * @param $key
     * @return string
     * @author Tao
     * @email  804633234@qq.com
     * @date 2022-08-13 11:16
     */
    public function DeRsaEcb($str,$key){
        $decrypted = openssl_decrypt(base64_decode($str), 'DES-EDE3',$key, OPENSSL_RAW_DATA);
        return $decrypted;
    }

JAVA


import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import com.hitrust.tech.util.Base64;

import java.io.FileInputStream;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Enumeration;
import java.util.HashMap;


class Main {
    public static String data="hello world";
    public static String publicKeyString="";
    public static String privateKeyString="";


    public static void main(String[] args) {
        //对称加密
        try {
            encryptDES("123","abcdefghizklmnopqrstuvwx");
        } catch (Exception e) {
            e.printStackTrace();
        }
        //对称解密
        try {
            decryptDES("qBSsv4QW65A=","abcdefghizklmnopqrstuvwx");
        } catch (Exception e) {
            e.printStackTrace();
        }

        //获取公钥
        PublicKey publicKey= null;
        try {
            publicKey = getPublicKey(publicKeyString);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //获取私钥
        PrivateKey privateKey= null;
        try {
            privateKey = getPrivateKey(privateKeyString);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //公钥加密
        byte[] encryptedBytes= new byte[0];
        try {
            encryptedBytes = encrypt(data.getBytes(), publicKey);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("加密后:"+new String(encryptedBytes));

        //私钥解密
        String keyStorefile = "C:\\Users\\Administrator\\Desktop\\siyao.pfx";
        String keyPassword = "000000";
        byte[] decryptedBytes= new byte[0];
        try {
            String str="";
            decryptedBytes = decrypt(str, getPvkformPfx(keyStorefile,keyPassword));
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("解密后:"+Base64.encode(decryptedBytes));


    }
    /**
     * @Description: 生成密钥, 返回168位的密钥
     * @return
     * @throws Exception
     */
    public static void generateKey() throws Exception {
        //实例化密钥生成器
        KeyGenerator kg = KeyGenerator.getInstance("DESede");
        //DESede 要求密钥长度为 112位或168位
        kg.init(168);
        //生成密钥
        SecretKey secretKey = kg.generateKey();
        //获得密钥的字符串形式
        System.out.println(new String(Base64.encode(secretKey.getEncoded())));
    }
    //dui
    public static void encryptDES(String paramString1, String key)
            throws Exception
    {
        byte[] keybyte = key.getBytes("utf-8");
        SecretKey deskey = new SecretKeySpec(keybyte, "DESede");
        byte[] input = paramString1.getBytes("UTF-8");
        Cipher c1 = Cipher.getInstance("DESede/ECB/PKCS5Padding");
        c1.init(Cipher.ENCRYPT_MODE, deskey);
        byte[] str1 = c1.doFinal(input);
        String str =Base64.encode(str1);
        System.out.println("jiamishuju:");
        System.out.println(str);
    }
    public static void decryptDES(String paramString1, String key)
            throws Exception
    {
        byte[] keybyte = key.getBytes("utf-8");
        SecretKey deskey2 = new SecretKeySpec(keybyte, "DESede");
        Cipher c2 = Cipher.getInstance("DESede");
        c2.init(Cipher.DECRYPT_MODE, deskey2);//加载解密算法
        byte[] str2 = c2.doFinal(Base64.decode(paramString1));//获得解密后的数据
        String string = new String(str2, "utf-8");
        System.out.println("jiemishuju:");
        System.out.println(string);
    }
    public static void decryptDES_(String paramString1, byte[] key)
            throws Exception
    {
        byte[] keybyte = key;
        SecretKey deskey2 = new SecretKeySpec(keybyte, "DESede");
        Cipher c2 = Cipher.getInstance("DESede");
        c2.init(Cipher.DECRYPT_MODE, deskey2);//加载解密算法
        byte[] str2 = c2.doFinal(Base64.decode(paramString1));//获得解密后的数据
        String string = new String(str2, "utf-8");
        System.out.println("jiemishuju:");
        System.out.println(string);
    }
    //将base64编码后的公钥字符串转成PublicKey实例
    public static PublicKey getPublicKey(String publicKey) throws Exception{
        byte[ ] keyBytes=publicKey.getBytes("utf-8");
        X509EncodedKeySpec keySpec=new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory=KeyFactory.getInstance("RSA");
        return keyFactory.generatePublic(keySpec);
    }

    //将base64编码后的私钥字符串转成PrivateKey实例
    public static PrivateKey getPrivateKey(String privateKey) throws Exception{
        byte[ ] keyBytes=privateKey.getBytes("utf-8");//Base64.getDecoder().decode(privateKey.getBytes());
        PKCS8EncodedKeySpec keySpec=new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory=KeyFactory.getInstance("RSA");
        return keyFactory.generatePrivate(keySpec);
    }

    //公钥加密
    public static byte[] encrypt(byte[] content, PublicKey publicKey) throws Exception{
        Cipher cipher=Cipher.getInstance("RSA");//java默认"RSA"="RSA/ECB/PKCS1Padding"
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        return cipher.doFinal(content);
    }

    //私钥解密
    public static byte[] decrypt(String str, PrivateKey privateKey) throws Exception{
        byte[] content=Base64.decode(str);
        Cipher cipher=Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        return cipher.doFinal(content);
    }
    /**
     * getPvkformPfx: 从PFX文件中获取私钥
     * @param strPfx 文件存储目录
     * @param strPassword PFX密码
     */
    private  static PrivateKey getPvkformPfx(String strPfx, String strPassword){
        try {
            FileInputStream fis = new FileInputStream(strPfx);
            //密码处理
            char[] nPassword = null;
            if ((strPassword == null) || strPassword.trim().equals("")){
                nPassword = null;
            } else {
                nPassword = strPassword.toCharArray();
            }
            //加载读取PFX文件
            KeyStore ks = KeyStore.getInstance("PKCS12");
            ks.load(fis, nPassword);
            fis.close();
            Enumeration enumas = ks.aliases();
            //从文件中获取秘钥
            String keyPFXFile = null;
            if (enumas.hasMoreElements()) {
                keyPFXFile = (String)enumas.nextElement();
            }
            PrivateKey prikey = (PrivateKey) ks.getKey(keyPFXFile, nPassword);
//            Certificate cert = (Certificate) ks.getCertificate(keyPFXFile);
//            PublicKey pubkey = cert.getPublicKey();
//            System.out.println("cert class = " + cert.getClass().getName());
//            System.out.println("cert = " + cert);
//            System.out.println("public key = " + pubkey);
//            System.out.println("private key = " + prikey);
//            System.out.println("private encode = " + Base64.encode(prikey.getEncoded()));
            return prikey;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }



}

XML

    /**
     * @desc RSA签名
     *
     * @param $str
     * @param $private_key
     * @return string
     * @author Tao
     * @email  804633234@qq.com
     * @date 2022-08-12 15:03
     */
    public  function Sign($str){
        $bufSignSrc =$str;
        $private_key = chunk_split($this->private_key , 64, "\n");
        $key = "-----BEGIN PRIVATE KEY-----\n".wordwrap($private_key)."-----END PRIVATE KEY-----";
        if(openssl_sign($bufSignSrc, $signature, $key )){
            //echo "success";
        }else{
            //echo 'sign fail';
        }
        $sign = base64_encode($signature);
        return $sign;
    }
   /**
     * @desc 数组转xml
     *
     * @param $header
     * @param $body
     * @return mixed
     * @author Tao
     * @email  804633234@qq.com
     * @date 2022-08-12 14:33
     */
    public function enxml($header, $body)
    {
        $headerxml = "";
        foreach ($header as $key => $val) {
            $headerxml .= "<$key>$val</$key>";
        }
        $bodyxml = "";
        foreach ($body as $key => $val) {
            $bodyxml .= "<$key>$val</$key>";
        }
        $xml = '<?xml version="1.0" encoding="utf-8"?><transaction><head>' . $headerxml . '</head><request>' . $bodyxml . '</request></transaction>';
        return $xml;
    }

    /**
     * @desc xml转数组
     *
     * @param $xml
     * @return array|mixed
     * @author Tao
     * @email  804633234@qq.com
     * @date 2022-08-12 14:33
     */
    public function dexml($xml)
    {
        try {
            return json_decode(json_encode(simplexml_load_string($xml)), true);
        } catch (\Throwable $exception) {
            return [];
        }
    }