文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

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

2023-09-28 17:12

关注

非对称加解密PHP

            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;    }        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));    }        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));    }        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);    }        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

        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;    }       public function enxml($header, $body)    {        $headerxml = "";        foreach ($header as $key => $val) {            $headerxml .= "<$key>$val";        }        $bodyxml = "";        foreach ($body as $key => $val) {            $bodyxml .= "<$key>$val";        }        $xml = '' . $headerxml . '' . $bodyxml . '';        return $xml;    }        public function dexml($xml)    {        try {            return json_decode(json_encode(simplexml_load_string($xml)), true);        } catch (\Throwable $exception) {            return [];        }    }

来源地址:https://blog.csdn.net/zhang804633234/article/details/126322165

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     807人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     351人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     314人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     433人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     221人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯