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加密,也就是公钥加密几种语言的总结