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