python、java RSA公私钥加密解密

本文介绍了使用Java和Python实现的RSA及AES加解密方法。包括私钥加密与公钥解密的过程,并提供了具体的代码实现。对于RSA部分,文章详细展示了如何利用私钥进行加密,再通过公钥进行解密;对于AES部分,则介绍了如何用相同的密钥完成加密与解密的操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

java RSA私钥加密、python公钥解密
python RSA公钥加密、java私钥解密
public static final String RSA = "RSA";
public static final String RSA_ECB_NO_PADDING = "RSA/ECB/PKCS1Padding";
public static final String AES_ECB_PKCS_5_PADDING = "AES/ECB/PKCS5Padding";
public static final String AES = "AES";

public static String rsaPrivateEncrypt(String privateKey, String data) {
    if (StringUtils.isBlank(data)) {
        return "";
    }
    try {
        KeyFactory keyFactory = KeyFactory.getInstance(RSA);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey));
        RSAPrivateKey key = (RSAPrivateKey) keyFactory.generatePrivate(pkcs8KeySpec);
        Cipher cipher = Cipher.getInstance(RSA_ECB_NO_PADDING);
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] bytes = cipher.doFinal(data.getBytes());
        return Base64.encodeBase64String(bytes);
    } catch (Exception e) {
        log.error("rsaPrivateEncrypt error", e);
    }
    return null;
}

public static String rsaPrivateDecrypt(String privateKey, String data) {
    if (StringUtils.isBlank(data)) {
        return "";
    }
    try {
        byte[] dataBytes = Base64.decodeBase64(data);
        KeyFactory keyFactory = KeyFactory.getInstance(RSA);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey));
        RSAPrivateKey key = (RSAPrivateKey) keyFactory.generatePrivate(pkcs8KeySpec);
        Cipher cipher = Cipher.getInstance(RSA_ECB_NO_PADDING);
        cipher.init(Cipher.DECRYPT_MODE, key);
        return new String(cipher.doFinal(dataBytes));
    } catch (Exception e) {
        log.error("rsaPrivateDecrypt error", e);
    }
    return null;
}

public static String aesEncrypt(String data, String key) {
    if (StringUtils.isBlank(data)) {
        return "";
    }
    try {
        Cipher cipher = Cipher.getInstance(AES_ECB_PKCS_5_PADDING);
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getBytes(), AES));
        return Base64.encodeBase64String(cipher.doFinal(data.getBytes(StandardCharsets.UTF_8)));
    } catch (Exception e) {
        log.error("aesDecryptData error", e);
    }
    return "";
}

public static String aesDecrypt(String data, String key) {
    if (StringUtils.isBlank(data)) {
        return "";
    }
    try {
        Cipher cipher = Cipher.getInstance(AES_ECB_PKCS_5_PADDING);
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key.getBytes(), AES));
        return new String(cipher.doFinal(Base64.decodeBase64(data)));
    } catch (Exception e) {
        log.error("aesDecryptData error", e);
    }
    return "";
}
import base64
import json
import random
import time
from urllib import parse

import requests
from Crypto.Cipher import AES, PKCS1_v1_5
from Crypto.PublicKey import RSA
from rsa import PublicKey, transform, core


def aes_encrypt(key, message):
    padding = lambda s: s + (16 - len(s) % 16) * chr(16 - len(s) % 16)
    txt = AES.new(key.encode(encoding="utf8"), AES.MODE_ECB).encrypt(padding(message).encode(encoding="utf8"))
    return base64.b64encode(txt)


def aes_decrypt(key, message):
    unpadding = lambda s: s[:-ord(s[len(s) - 1:])]
    base64_decrypted = base64.decodebytes(message.encode(encoding='utf-8'))
    string = str(AES.new(key.encode(encoding="utf8"), AES.MODE_ECB).decrypt(base64_decrypted), encoding='utf-8')
    return unpadding(string)


def decrypt_by_public_key(publickey, message):
    rsa_public_key = PublicKey.load_pkcs1_openssl_der(base64.b64decode(publickey))
    text_str = transform.bytes2int(base64.b64decode(message))
    final_text = transform.int2bytes(core.decrypt_int(text_str, rsa_public_key.e, rsa_public_key.n))
    final_qr_code = final_text[final_text.index(0) + 1:]
    return final_qr_code.decode()


def encrypt_by_public_key(publickey, message):
    byte = PKCS1_v1_5.new(RSA.importKey(base64.b64decode(publickey))).encrypt(message.encode(encoding="utf8"))
    return base64.b64encode(byte).decode(encoding="utf8")
### 回答1: Python RSA 加密和解密文件的基本流程如下: 1. 使用 RSA 库生成公钥私钥。 2. 使用公钥对文件进行加密。 3. 使用私钥对加密后的文件进行解密。 示例代码: ``` from Crypto.PublicKey import RSA from Crypto.Cipher import PKCS1_OAEP # 生成公钥私钥 key = RSA.generate(2048) private_key = key.export_key() public_key = key.publickey().export_key() # 使用公钥加密文件 with open("original_file.txt", "rb") as f: original_data = f.read() cipher = PKCS1_OAEP.new(RSA.import_key(public_key)) encrypted_data = cipher.encrypt(original_data) with open("encrypted_file.bin", "wb") as f: f.write(encrypted_data) # 使用私钥解密文件 with open("encrypted_file.bin", "rb") as f: encrypted_data = f.read() cipher = PKCS1_OAEP.new(RSA.import_key(private_key)) decrypted_data = cipher.decrypt(encrypted_data) with open("decrypted_file.txt", "wb") as f: f.write(decrypted_data) ``` 请注意,上面的代码仅用于示例目的,实际应用中需要注意密钥的安全存储。 ### 回答2: RSA加密算法是一种非对称加密算法,它使用一对相互关联的公钥私钥进行加解密公钥用于加密数据,而私钥用于解密数据。 在使用Python进行RSA解密文件时,我们首先需要生成一对公私钥。可以使用`rsa`库中的`newkeys()`函数来生成密钥对。例如,以下代码将生成一对2048位的公私钥: ``` from rsa import newkeys # 生成一对公私钥 (pub_key, priv_key) = newkeys(2048) ``` 接下来,我们可以使用公私钥进行文件的加解密操作。以下是一个使用RSA解密文件的示例代码: ``` from rsa import encrypt, decrypt # 加密文件 def encrypt_file(file_path, output_path, pub_key): with open(file_path, 'rb') as file: data = file.read() enc_data = encrypt(data, pub_key) with open(output_path, 'wb') as output_file: output_file.write(enc_data) # 解密文件 def decrypt_file(file_path, output_path, priv_key): with open(file_path, 'rb') as file: enc_data = file.read() dec_data = decrypt(enc_data, priv_key) with open(output_path, 'wb') as output_file: output_file.write(dec_data) ``` 在使用以上代码时,需要指定待加密的文件路径、加密后的文件输出路径以及公私钥。可以通过`pub_key.save_pkcs1()`和`priv_key.save_pkcs1()`方法将密钥保存到文件以便后续使用。 需要注意的是,RSA加密算法会对数据进行分块加解密,因此对于较大的文件,可能需要分块加密再拼接。另外,RSA加密算法的运算耗时较长,因此在实际使用中可能需要将其用在对安全性要求较高的场景。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值