常用的加解密技术有哪些?利用Java、Python实现RSA、DSA

常用的加解密技术有哪些?利用Java、Python实现RSA、DSA

编码文章call10242025-01-06 21:00:3023A+A-

本文主要讲非对称加密:使用一对密钥进行加密和解密的技术。其中,一个密钥用于加密,另一个密钥用于解密。

RSA(算法的名字以发明者的名字命名:Ron Rivest, AdiShamir 和Leonard Adleman)

DSA(Digital Signature Algorithm,数字签名)

1.下面是使用Java实现RSA加解密算法:

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import javax.crypto.Cipher;

/**
 * 使用RSA加解密示例
 */
public class RSAEncrypt {
    /**
     * Rsa加密算法
     * @param publicKey 公钥
     * @param content 需要加密的内容
     * @return 返回加密结果
     * @throws Exception
     */
    public static byte[] encrypt(PublicKey publicKey, byte[] content) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");  // 创建RSA加密器
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);  // 初始化加密器
        return cipher.doFinal(content);  // 加密
    }

    /**
     * RSA解密算法
     * @param privateKey 私钥
     * @param cipherText 解密内容
     * @return  返回原文
     * @throws Exception
     */
    public static byte[] decrypt(PrivateKey privateKey, byte[] cipherText) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");  // 创建RSA解密器
        cipher.init(Cipher.DECRYPT_MODE, privateKey);  // 初始化解密器
        return cipher.doFinal(cipherText);  // 解密
    }

    public static void main(String[] args) throws Exception {
        // 生成密钥对
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(2048);  // 密钥长度为2048位
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        PublicKey publicKey = keyPair.getPublic();
        PrivateKey privateKey = keyPair.getPrivate();
        //在使用该代码时请一定概要将key 保存至配置文件

        // 加密
        String content = "Hello, World!";  // 加密内容
        byte[] cipherText = encrypt(publicKey, content.getBytes());

        // 解密
        byte[] plainText = decrypt(privateKey, cipherText);

        System.out.println(new String(plainText));  // 打印解密后的结果
    }
}

2.DSA是一种用于数字签名的算法,它用于生成和验证数字签名。下面是一个使用Java实现DSA数字签名的例子:

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;

public class DSAExample {
  public static void main(String[] args) throws Exception {
    // Generate a key pair
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA");
    keyGen.initialize(1024);
    KeyPair keyPair = keyGen.generateKeyPair();
    PrivateKey privateKey = keyPair.getPrivate();
    PublicKey publicKey = keyPair.getPublic();

    // Sign the data
    Signature signature = Signature.getInstance("SHA1withDSA");
    signature.initSign(privateKey);
    byte[] data = "Hello, World!".getBytes("UTF-8");
    signature.update(data);
    byte[] signatureBytes = signature.sign();

    // Verify the signature
    signature.initVerify(publicKey);
    signature.update(data);
    boolean verified = signature.verify(signatureBytes);
    System.out.println("Signature verified: " + verified);
  }
}

在这个例子中,我们首先使用KeyPairGenerator生成一对DSA密钥。其中,私钥用于签名,公钥用于验证签名。

然后,我们使用Signature类初始化签名。在这里,我们使用"SHA1withDSA"算法,这是一种DSA签名算法。

接下来,我们使用私钥对数据进行签名。我们需要使用update()方法将数据添加到签名中,然后调用sign()方法生成签名。

最后,我们使用公钥对签名进行验证。我们需要使用update()方法将数据添加到签名中,然后调用verify()方法验证签名是否有效。

3.下面是一个使用Python实现RSA加密的例子:

from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP

def encrypt(public_key_loc, message):
  # Read the public key
  key = open(public_key_loc, "r").read()
  rsakey = RSA.importKey(key)
  cipher = PKCS1_OAEP.new(rsakey)

  # Encrypt the message
  encrypted_message = cipher.encrypt(message)
  return encrypted_message

def decrypt(private_key_loc, encrypted_message):
  # Read the private key
  key = open(private_key_loc, "r").read()
  rsakey = RSA.importKey(key)
  cipher = PKCS1_OAEP.new(rsakey)

  # Decrypt the message
  message = cipher.decrypt(encrypted_message)
  return message

def sign(private_key_loc, message):
  # Read the private key
  key = open(private_key_loc, "r").read()
  rsakey = RSA.importKey(key)
  signer = PKCS1_OAEP.new(rsakey)

  # Sign the message
  signature = signer.sign(message)
  return signature

def verify(public_key_loc, message, signature):
  # Read the public key
  key = open(public_key_loc, "r").read()
  rsakey = RSA.importKey(key)
  verifier = PKCS1_OAEP.new(rsakey)

  # Verify the signature
  try:
    verifier.verify(message, signature)
    return True
  except (ValueError, TypeError):
    return False

这个例子中,我们使用了Python的Crypto库来实现RSA算法。 这个例子包含了四个函数:encrypt()用于加密数据,decrypt()用于解密数据,sign()用于生成数字签名,verify()用于验证数字签名。 你可以使用这些函数来对数据进行加密、解密、签名和验证操作。

4.DSA(Digital Signature Algorithm)是一种用于数字签名的算法,它使用数字密钥进行加密

生成DSA密钥对:

from Crypto.PublicKey import DSA

# 生成DSA密钥对
key = DSA.generate(1024)

# 获取公钥
public_key = key.publickey().exportKey()

# 获取私钥
private_key = key.exportKey()

签名数据和验证数字签名:

from Crypto.Hash import SHA
from Crypto.PublicKey import DSA

# 使用私钥签名数据
data = b'Hello, World!'
h = SHA.new(data)
signature = key.sign(h)

# 使用公钥验证数字签名
h = SHA.new(data)
verification = key.verify(h, signature)
print(verification)  # 输出True

示例用于提升对算法的印象。

点击这里复制本文地址 以上内容由文彬编程网整理呈现,请务必在转载分享时注明本文地址!如对内容有疑问,请联系我们,谢谢!
qrcode

文彬编程网 © All Rights Reserved.  蜀ICP备2024111239号-4