python Crypto 使用已有公钥加密数据进行传输

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

#从url获取内容
req = requests.get("your url");
result = req.text
test = json.loads(result)

#获取json中的密钥和验证码,这个根据各自的json不同有所差异,此处只举例
public  = test['data']['publicKey']
verifyKey = test['data']['verifyKey']

message = 'your message'
public_key_str = "-----BEGIN RSA PUBLIC KEY-----\n{}\n-----END RSA PUBLIC KEY-----".format(public).encode()
#转换为公钥对象
cipher_public =PKCS1_v1_5.new(RSA.importKey(public_key_str))
#加密需要加密的内容
text_encrypted = cipher_public.encrypt(message.encode())
text = base64.b64encode(text_encrypted).decode()

#打印
print(text)
print(verifyKey)

备注:crypto pip安装后会出现问题,原因是安装后在lib中库文件夹是小写crypto 要改成大写Crypto 才能调用。小BUG需要手动排除。

JAVA版本

package test2;
import java.security.*;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.*;  
import java.util.Base64;
import java.util.Base64.Decoder;
import java.util.Base64.Encoder;  


public class RSAEncryptionExample {  
    public static String encodeBase64(byte[] binaryData) {
    	Encoder encoder = Base64.getEncoder();
        return encoder.encodeToString(binaryData);
    }
 
    public static byte[] decodeBase64(String encoded) {
        Decoder decoder = Base64.getDecoder();
        return decoder.decode(encoded);
    }	

    public static byte[] encryptPublicKey(byte[] binaryData, String publicKey) throws Exception {
        byte[] keyBytes = decodeBase64(publicKey);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        
        // 获取RSA算法实例
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        Key pubKey = keyFactory.generatePublic(keySpec);
        
        // 初始化加密器
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);
        return cipher.doFinal(binaryData);
    }
	public static void main(String[] args) throws Exception {
		String content = "your 需要加密的数据";
		System.out.println("============   分隔符     ===========");
		String publickey = "your 公钥字符串";
		byte[] encodeContent2 = encryptPublicKey(content.getBytes(),publickey);
		System.out.println("公钥加密后的数据:"+Base64.getEncoder().encodeToString(encodeContent2));
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值