添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
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;
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;
     * @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 [];
1、一般由服务器创建秘钥对,私钥保存在服务器,公钥下发至客户端
2、公钥是二进制数据,怎么下发给客户端呢?
第一种方式:服务器把二进制数据写入文件,然后把文件传给客户端。由客户端从文件读取二进制数据。
第二种方式:服务器把二进制数据转成 base64 字符串,客户端获取到 base64 字符串后,再转码为二进制数据。
我们封存一
                                    最近遇到一个项目,需要进行RSA的验签,RSA的密钥为2048位即256个字节长。
上游是先对一个文件进行SHA256做hash,得到32字节的摘要,然后进行填充,填充规则为前面两个字节为0x00,0x01,然后填充全FF,接下来是32字节的摘要数据,这样填充之后的总数据长度为256字节,然后使用RSA的私钥对这256字节进行签名,下发下来,下游需要对这个签名进行处理,得到原始摘要,然后跟自己计算的摘要比对,验证通过则合法。
涉及的知识点如下:
一、RSA签名算法的填充方式,常用的有如下三种
import java.lang.reflect.Method;  
import java.security.*;  
import java.security.spec.*;  
import java.
//公钥(注意包括头(-----BEGIN PUBLIC KEY-----)尾(-----END PUBLIC KEY-----)标志)
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDbdq5NjtUEkAQ6wucPuhC0aRvSMsaX3GrhkwsLLdWZnVNVpkJRw
yPFq9HJNuntRw7P9Sb3Tk.
否则,会报错:“data too large for modulus”,这个是正常的,否则大于模数肯定解密不出,因为要取模的。
因此,在读取文件加密时,每次读取128字节时,有可能大于模数,因此需要判断;大于模数时,读取127字节。
但问题也出来了:解密出来怎么判断第一个00是真实数据,还是需要去掉的呢?(如果00xy...,可以判断
public static Pair<String,String> createPubPrivateKey() throws Exception {
   // 公钥私钥构建器
   KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
   // 初始化大小,64的整数倍
   keyPairGenerator.initialize(512);
                                    public static String passEncipher(String password) throws Exception {
		String pKey = "xxxxxxxx";
		byte[] keyByte = Base64.decode(pKey.getBytes("UTF-8"), Base64.NO_WRAP);
		KeyFactory keyFactory = KeyFactory.getInstance("RSA");// KEY_ALGORITHM 指定的加密算法
                                    JS实现RSA/ECB/PKCS1Padding的私钥加密代码pkcs1pad1的实现调用方式
题目是私钥加密,为啥要写,就是因为目前网络能搜到的库,都没有这个算法。不管是jsencrypt.js,还是js-rsa-security.js,还是kjur-jsrsasign-d282c71,加密算法其实都一样的函数,不知道为啥取了不同的名字。
代码是直接在kjur-jsrsasign-d282...