国标非对称加密:RSA算法、非对称特征、js还原、jsencrypt和rsa模块解析

🔒 国标非对称加密:RSA算法、非对称特征、js还原、jsencrypt和rsa模块解析

🔑 RSA 算法原理

RSA(Rivest-Shamir-Adleman)是一种广泛使用的非对称加密算法。它利用了大数因数分解的困难性来确保加密的安全性。RSA 算法的关键特征在于它使用一对密钥:公钥和私钥。公钥用于加密数据,而私钥用于解密数据。

算法原理

1. 密钥生成
  • 选择两个大质数:选择两个足够大的质数 ( p ) 和 ( q )。
  • 计算模数 ( n ): ( n = p \times q )。模数 ( n ) 是公钥和私钥的一部分。
  • 计算 ( \phi(n) ):( \phi(n) = (p-1) \times (q-1) ),这是 ( n ) 的欧拉函数。
  • 选择公钥指数 ( e ):选择一个与 ( \phi(n) ) 互质的整数 ( e ),通常选择 65537。
  • 计算私钥指数 ( d ):计算 ( d ) 使得 ( d \times e \equiv 1 \mod \phi(n) )。
2. 加密与解密
  • 加密:使用公钥 ( (e, n) ) 将明文消息 ( M ) 加密为密文 ( C ),公式为 ( C = M^e \mod n )。
  • 解密:使用私钥 ( (d, n) ) 将密文 ( C ) 解密回明文 ( M ),公式为 ( M = C^d \mod n )。

Python 实现

使用 cryptography 库来实现 RSA 加密和解密:

from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding

def generate_keys():
    # 生成 RSA 密钥对
    private_key = rsa.generate_private_key(
        public_exponent=65537,
        key_size=2048,
    )
    public_key = private_key.public_key()
    return private_key, public_key

def encrypt_message(message, public_key):
    # 加密消息
    encrypted_message = public_key.encrypt(
        message.encode('utf-8'),
        padding.OAEP(
            mgf=padding.MGF1(algorithm=hashes.SHA256()),
            algorithm=hashes.SHA256(),
            label=None
        )
    )
    return encrypted_message

def decrypt_message(encrypted_message, private_key):
    # 解密消息
    decrypted_message = private_key.decrypt(
        encrypted_message,
        padding.OAEP(
            mgf=padding.MGF1(algorithm=hashes.SHA256()),
            algorithm=hashes.SHA256(),
            label=None
        )
    )
    return decrypted_message.decode('utf-8')

# 示例
private_key, public_key = generate_keys()
message = "Hello, RSA!"
encrypted_message = encrypt_message(message, public_key)
decrypted_message = decrypt_message(encrypted_message, private_key)

print("Encrypted Message:", encrypted_message)
print("Decrypted Message:", decrypted_message)

输入输出示例:

  • 输入: 明文消息 "Hello, RSA!"
  • 输出:
    • 加密结果: b'\x98\x0b\x0b\xea...' (加密的密文)
    • 解密结果: "Hello, RSA!"

JavaScript 实现(使用 jsencrypt 模块)

const JSEncrypt = require('jsencrypt').JSEncrypt;

function rsaEncryptDecrypt(message, publicKey, privateKey, mode) {
    const encryptor = new JSEncrypt();
    encryptor.setPublicKey(publicKey);
    encryptor.setPrivateKey(privateKey);

    if (mode === 'encrypt') {
        return encryptor.encrypt(message);
    } else if (mode === 'decrypt') {
        return encryptor.decrypt(message);
    } else {
        throw new Error("Invalid mode. Choose 'encrypt' or 'decrypt'.");
    }
}

// 示例
const publicKey = `-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA7ZgMciTp...
-----END PUBLIC KEY-----`;
const privateKey = `-----BEGIN PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFA...
-----END PRIVATE KEY-----`;
const message = 'Hello, RSA!';
const encrypted = rsaEncryptDecrypt(message, publicKey, privateKey, 'encrypt');
const decrypted = rsaEncryptDecrypt(encrypted, publicKey, privateKey, 'decrypt');

console.log("Encrypted:", encrypted);
console.log("Decrypted:", decrypted);

输入输出示例:

  • 输入: 明文消息 "Hello, RSA!", 公钥和私钥 (PEM 格式)
  • 输出:
    • 加密结果: "U2FsdGVkX1+...lCw==" (加密的密文)
    • 解密结果: "Hello, RSA!"

🌟 非对称加密的特征

1. 非对称特性

非对称加密的主要特征是使用一对密钥:公钥和私钥。公钥用于加密,私钥用于解密。与对称加密不同,非对称加密的安全性依赖于密钥的管理和算法的复杂性。

2. 安全性

RSA 算法的安全性依赖于大数因数分解的困难性。即使知道公钥,也无法轻易推算出私钥,这使得 RSA 算法在传输敏感数据时具有较高的安全性。

3. 公私钥对

在实际应用中,公钥可以公开,而私钥必须保密。公钥可以用于加密数据,而只有私钥持有者才能解密这些数据。

🌐 JavaScript 中的 RSA 实现

使用 jsencrypt 模块

jsencrypt 是一个轻量级的 RSA 加密模块,支持在浏览器环境和 Node.js 环境中使用。它提供了简单的接口来进行 RSA 加密和解密。

代码示例
const JSEncrypt = require('jsencrypt').JSEncrypt;

function rsaEncryptDecrypt(message, publicKey, privateKey, mode) {
    const encryptor = new JSEncrypt();
    encryptor.setPublicKey(publicKey);
    encryptor.setPrivateKey(privateKey);

    if (mode === 'encrypt') {
        return encryptor.encrypt(message);
    } else if (mode === 'decrypt') {
        return encryptor.decrypt(message);
    } else {
        throw new Error("Invalid mode. Choose 'encrypt' or 'decrypt'.");
    }
}

// 示例
const publicKey = `-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA7ZgMciTp...
-----END PUBLIC KEY-----`;
const privateKey = `-----BEGIN PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFA...
-----END PRIVATE KEY-----`;
const message = 'Hello, RSA!';
const encrypted = rsaEncryptDecrypt(message, publicKey, privateKey, 'encrypt');
const decrypted = rsaEncryptDecrypt(encrypted, publicKey, privateKey, 'decrypt');

console.log("Encrypted:", encrypted);
console.log("Decrypted:", decrypted);

输入输出示例:

  • 输入: 明文消息 "Hello, RSA!", 公钥和私钥 (PEM 格式)
  • 输出:
    • 加密结果: "U2FsdGVkX1+...lCw==" (加密的密文)
    • 解密结果: "Hello, RSA!"

🛠️ 拓展用法

1. 密钥管理

Python 实现:

from cryptography.hazmat.primitives import serialization

def save_key_to_file(key, file_name):
    with open(file_name, 'wb') as key_file:
        key_file.write(key)

def load_key_from_file(file_name):
    with open(file_name, 'rb') as key_file:
        key = key_file.read()
    return key

# 示例
private_key_pem = private_key.private_bytes(
    encoding=serialization.Encoding.PEM,
    format=serialization.PrivateFormat.TraditionalOpenSSL,
    encryption_algorithm=serialization.NoEncryption()
)
public_key_pem = public_key.public_bytes(
    encoding=serialization.Encoding.PEM,
    format=serialization.PublicFormat.SubjectPublicKeyInfo
)

save_key_to_file(private_key_pem, 'private_key.pem')
save_key_to_file(public_key_pem, 'public_key.pem')

loaded_private_key = load_key_from_file('private_key.pem')
loaded_public_key = load_key_from_file('public_key.pem')

2. 密钥加密

Python 实现:

from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.kdf.pbk

df2 import PBKDF2HMAC
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from cryptography.hazmat.primitives import serialization

def encrypt_key_with_password(key, password):
    kdf = PBKDF2HMAC(
        algorithm=hashes.SHA256(),
        length=32,
        salt=b'some_salt',
        iterations=100000,
    )
    encrypted_key = kdf.derive(password)
    return encrypted_key

def decrypt_key_with_password(encrypted_key, password):
    kdf = PBKDF2HMAC(
        algorithm=hashes.SHA256(),
        length=32,
        salt=b'some_salt',
        iterations=100000,
    )
    decrypted_key = kdf.verify(password, encrypted_key)
    return decrypted_key

# 示例
password = b'secret_password'
encrypted_key = encrypt_key_with_password(public_key_pem, password)
decrypted_key = decrypt_key_with_password(encrypted_key, password)

3. 密钥对生成与导入导出

Python 实现:

from cryptography.hazmat.primitives.asymmetric import rsa

def generate_and_export_key_pair():
    private_key = rsa.generate_private_key(
        public_exponent=65537,
        key_size=2048,
    )
    public_key = private_key.public_key()
    
    private_key_pem = private_key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.TraditionalOpenSSL,
        encryption_algorithm=serialization.NoEncryption()
    )
    public_key_pem = public_key.public_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PublicFormat.SubjectPublicKeyInfo
    )
    
    with open('private_key.pem', 'wb') as private_key_file:
        private_key_file.write(private_key_pem)
        
    with open('public_key.pem', 'wb') as public_key_file:
        public_key_file.write(public_key_pem)

# 示例
generate_and_export_key_pair()

4. 通过密钥对进行加密和解密

Python 实现:

def rsa_encrypt_decrypt(message, public_key_pem, private_key_pem, mode):
    public_key = serialization.load_pem_public_key(public_key_pem)
    private_key = serialization.load_pem_private_key(private_key_pem, password=None)
    
    if mode == 'encrypt':
        return encrypt_message(message, public_key)
    elif mode == 'decrypt':
        return decrypt_message(message, private_key)
    else:
        raise ValueError("Invalid mode. Choose 'encrypt' or 'decrypt'.")

# 示例
message = "Hello, RSA!"
encrypted = rsa_encrypt_decrypt(message, public_key_pem, private_key_pem, 'encrypt')
decrypted = rsa_encrypt_decrypt(encrypted, public_key_pem, private_key_pem, 'decrypt')

print("Encrypted:", encrypted)
print("Decrypted:", decrypted)

5. 密钥对比和验证

Python 实现:

def compare_keys(key1, key2):
    return key1 == key2

# 示例
public_key_1 = load_key_from_file('public_key.pem')
public_key_2 = load_key_from_file('public_key.pem')

print("Keys are equal:", compare_keys(public_key_1, public_key_2))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Switch616

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值