RSA-动态加密-openssl加密-常见语言集合

7 篇文章 0 订阅
1 篇文章 0 订阅

openssl_pkey_get_public加密,也就是公钥加密的总结

一、PHP语言

1、加密

//加密
public static function encryptData($string){
    $ssl_public = file_get_contents("public.key");//读取公钥文件
    $pu_key = openssl_pkey_get_public($ssl_public);//这个函数可用来判断公钥是否是可用的
    if (false == $pu_key) return '证书错误';
    openssl_public_encrypt($string, $data, $pu_key);//公钥加密
    $data = base64_encode($data);
    return $data;
}

2、POST请求封装

function http_post($url, $header, $data){
    $headers[] = "Accept:application/json";
    $headers[] = "Content-Type:application/json";
    $headers[] = "User-Agent:application/json";
    $headers[] = $header;

    $curl = curl_init(); // 启动一个CURL会话
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HEADER, 0);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    $tmpInfo = curl_exec($curl);
    //关闭URL请求
    curl_close($curl);
    return $tmpInfo;
}

3、发送数据

$data = [
    "cell_phone_number" =>  ['15056988888','15056989999','15056987777'],
    "callback_url"  =>  "http://www.baidu.com"
];
$headers = array(
    'Authorization:'.Encrypt::encryptData('3ce886c7-53ee-4340-a4d0-b460d95c4388')
);
$res = http_post("http://www.baidu.com",$headers,$data);
var_dump($res)

二、go语言

1、POST请求数据及RSA头加密

package controller

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"encoding/base64"
	"encoding/json"
	"encoding/pem"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"net/http"
	"strings"
	"time"
)

type DataInfo struct {
	BatchNumber string `json:"batch_number"`
}

type ContentResponse struct {
	Code    int      `json:"code"`
	Message string   `json:"message"`
	Time    int      `json:"time"`
	Data    DataInfo `json:"data"`
}

func CheckVictimPhone(c *gin.Context) {
	// 读取公钥文件
	pubFile, _ := ioutil.ReadFile("public.key")
	// 初始化公钥文件
	block, _ := pem.Decode(pubFile)
	// 转变公钥文件
	pub, _ := x509.ParsePKIXPublicKey(block.Bytes)
	// 获取key
	pubKey, _ := pub.(*rsa.PublicKey)
	// 需要加密的数据
	data := []byte("3ce886c7-53ee-4340-a4d0-b460d95c4388")
	// 加密数据
	encryData, err := rsa.EncryptPKCS1v15(rand.Reader, pubKey, data)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    50000,
			"message": err.Error(),
			"time":    time.Now().Unix(),
		})
		return
	}
	// 赋值授权码
	Authorization := base64.StdEncoding.EncodeToString(encryData)

	bodyContent := "{\"cell_phone_number\":[\"15056988888\",\"15056989999\",\"15056987777\"],\"callback_url\":\"http://www.baidu.com\"}"
	// 创建请求
	req, err := http.NewRequest("POST", "http://www.baidu.com", strings.NewReader(bodyContent))
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    50000,
			"message": err.Error(),
			"time":    time.Now().Unix(),
		})
		return
	}
	// 设置Content-Type
	req.Header.Set("User-Agent", "Mozilla/5.0")
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", Authorization)
	// 发送请求
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    50000,
			"message": err.Error(),
			"time":    time.Now().Unix(),
		})
		return
	}
	//关闭资源体
	defer resp.Body.Close()
	//读取body内容
	content, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    50000,
			"message": err.Error(),
			"time":    time.Now().Unix(),
		})
		return
	}
	// 定义返回结构体
	var response ContentResponse
	// 解析 JSON 到 Go 对象
	json.Unmarshal([]byte(content), &response)

	c.JSON(http.StatusOK, gin.H{
		"code":    response.Code,
		"message": response.Message,
		"time":    response.Time,
		"data":    response.Data,
	})
	return
}

三、Java语言

1、POST请求数据及RSA头加密

import javax.crypto.Cipher;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

public class RSAPublicEncrypt {
    public static void main(String[] args) throws Exception {
        // 公钥字符串
        String publicKeyString = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCtmxAdCgYpPcPfi4PKkkDwBfnw3XE4GLOKgIGNRxbEwYg7UU4CxUxkBVJ9IhUz3iXKDjHmE8volydtw8xsWRmRmrxbvEKKJi3UGdCyD3mNc4pd8aRMbgwNLVWEj5lqFuMVu+B1JhU7Z";
        // 转换公钥
        byte[] publicKeyBytes = Base64.getDecoder().decode(publicKeyString);
        // 公钥实例化
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey publicKey = keyFactory.generatePublic(keySpec);
        // 公钥加密
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        // 授权码字符串
        String data = "3ce886c7-53ee-4340-a4d0-b460d95c4388";
        // RSA加密授权码字符串
        byte[] encryptedData = cipher.doFinal(data.getBytes());
        // 加密授权码
        String Authorization = Base64.getEncoder().encodeToString(encryptedData);
        // 地址
        String serverURL = "http://www.baidu.com";
        try{
            // 创建URL对象
            URL url = new URL(serverURL);
            // 创建HttpURLConnection对象
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 设置请求方法为POST
            connection.setRequestMethod("POST");
            // 添加请求头
            connection.setRequestProperty("User-Agent", "Mozilla/5.0");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Authorization", Authorization);
            // 启用输出流,并指定请求体的内容
            connection.setDoOutput(true);
            String requestBody = "{\"cell_phone_number\":[\"15056988888\",\"15056989999\",\"15056987777\"], \"callback_url\":\"http://www.baidu.com\"}";
            DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
            outputStream.writeBytes(requestBody);
            outputStream.flush();
            outputStream.close();
            // 获取响应码
            int responseCode = connection.getResponseCode();
            // 读取响应内容
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            StringBuilder response = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();
            //响应结果
            System.out.println("Response Code: " + responseCode);
            System.out.println("Response Body: " + response.toString());
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

四、pythen语言

1、POST请求数据及RSA头加密

# _*_ coding: utf-8 _*_

"""
RSA加密
Key长度2048
"""
import json

from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
import base64
import requests

def handle_pub_key(key):
    """
    处理公钥
    公钥格式pem,处理成以-----BEGIN PUBLIC KEY-----开头,-----END PUBLIC KEY-----结尾的格式
    :param key:pem格式的公钥,无-----BEGIN PUBLIC KEY-----开头,-----END PUBLIC KEY-----结尾
    :return:
    """
    start = '-----BEGIN PUBLIC KEY-----\n'
    end = '-----END PUBLIC KEY-----'
    result = ''
    # 分割key,每64位长度换一行
    divide = int(len(key) / 64)
    divide = divide if (divide > 0) else divide + 1
    line = divide if (len(key) % 64 == 0) else divide + 1
    for i in range(line):
        result += key[i * 64:(i + 1) * 64] + '\n'
    result = start + result + end
    return result

def encrypt(key, content):
    """
    ras 加密[公钥加密]
    :param key: 无BEGIN PUBLIC KEY头END PUBLIC KEY尾的pem格式key
    :param content:待加密内容
    :return:
    """
    pub_key = handle_pub_key(key)
    pub = RSA.import_key(pub_key)
    cipher = PKCS1_v1_5.new(pub)
    encrypt_bytes = cipher.encrypt(content.encode(encoding='utf-8'))
    result = base64.b64encode(encrypt_bytes)
    result = str(result, encoding='utf-8')
    return result

def post_url(url,auth,data):
    """
    post 请求
    :param url: 请求地址
    :param auth: 授权加密值
    :param data: 发送数据
    :return:
    """
    # 设置授权头信息
    headers = {
        'User-Agent': 'Mozilla/5.0',  # 设置User-Agent信息
        'Content-Type': 'application/json',
        'Authorization': auth   # 设置授权信息
    }
    # 发送请求
    return requests.post(url, data=data, headers=headers)

if __name__ == '__main__':
    # 公钥数据
    public_data = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCtmxAdCgYpPcPfi4PKkkDwBfnw3XE4GLOKgIGNRxbEwYg7UU4CxUxkBVJ9IhUz3iXKDjHmE8volydtw8xsWRmRmrxbvEKKJi3UGdCyD3mNc4pd8aRMbgwNLVWEj5lqFuMVu+B1JhU7"
    # 未加密Authorization数据
    Authorization_data = "3ce886c7-53ee-4340-a4d0-b460d95c4388"
    # 针对Authorization数据加密
    Authorization_encrypt = encrypt(public_data,Authorization_data)
    # 组合要发送的数据
    data = {
        'cell_phone_number': ['15056988888','15056989999','15056987777'], #需要检测的手机号
        'callback_url':'http://www.baidu.com'    #回调地址
    }
    # 调用函数发送请求
    response = post_url("http://www.baidu.com",Authorization_encrypt,json.dumps(data))
    # 处理请求响应
    res = response.json()
    # 请求成功的情况下请保存批次号。检测完毕之后,也是按照批次号对应推送的
    if res['code'] == 20000:
        print("本次发送的批次号:",res['data']['batch_number'])
    else:
        print("本次提交的错误",res['message'])

openssl_pkey_get_public加密,也就是公钥加密几种语言的总结

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用字符串公钥进行RSA-512加密的步骤: 1. 将字符串公钥转换为RSA公钥对象。如果字符串公钥是PEM格式的,可以使用openssl库中的函数进行转换。如果是其他格式的字符串公钥,需要根据具体的格式进行转换。 2. 将待加密的明文转换为字节串。 3. 使用RSA公钥对象对明文进行加密。可以使用Python中的cryptography库中的RSA加密方法进行加密。 4. 将加密后的密文转换为字符串。 下面是一个示例代码,假设字符串公钥是PEM格式的: ```python from cryptography.hazmat.primitives.asymmetric import rsa, padding from cryptography.hazmat.primitives import serialization from cryptography.hazmat.backends import default_backend # 将PEM格式的字符串公钥转换为RSA公钥对象 public_key_str = "-----BEGIN PUBLIC KEY-----\nMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDZ8cC7fdsVv+OJyGtLJQHfO12u\n6F3eNQKWv2+HwVxan2V1W/8DpXHfG9g3eJ8N5k+2OYCE3yjIhC5FwRoVcvU8Tg7J\ndF4E5sa6v6QfJkJ1Jr7+5C2BZtLv7L3u3XJyG4K5/cv+YiW0G8uJdiBhOQyW7yFq\n2Kv2Zt8tZ7u1nY9TQQIDAQAB\n-----END PUBLIC KEY-----" public_key = serialization.load_pem_public_key(public_key_str.encode(), backend=default_backend()) # 待加密的明文 plaintext = b"Hello, world!" # 使用RSA公钥对象进行加密 ciphertext = public_key.encrypt( plaintext, padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None ) ) # 将加密后的密文转换为字符串 ciphertext_str = ciphertext.hex() print(ciphertext_str) ``` 注意,这里使用的是RSA-OAEP填充方式进行加密,可以提供更好的安全性。加密后的密文是一个字节串,可以使用hex()方法将其转换为字符串。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值