Bouncy Castle 用法
时间: 2023-11-15 12:04:36 浏览: 34
Bouncy Castle 是一个在 Java 平台上提供密码学功能的开源库。它提供了一套丰富的密码学算法和协议的实现,包括对称加密、非对称加密、哈希函数、数字签名、密钥交换等。
以下是使用 Bouncy Castle 的一些基本用法示例:
1. 对称加密:
```java
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.Security;
public class SymmetricEncryptionExample {
public static void main(String[] args) throws Exception {
Security.addProvider(new BouncyCastleProvider());
byte[] keyBytes = "0123456789abcdef".getBytes(); // 密钥,16字节
byte[] plaintext = "Hello, Bouncy Castle!".getBytes(); // 明文
SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding", "BC");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] ciphertext = cipher.doFinal(plaintext);
System.out.println("Ciphertext: " + new String(ciphertext));
}
}
```
2. 非对称加密:
```java
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.Security;
import javax.crypto.Cipher;
public class AsymmetricEncryptionExample {
public static void main(String[] args) throws Exception {
Security.addProvider(new BouncyCastleProvider());
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA", "BC");
keyGen.initialize(2048);
KeyPair keyPair = keyGen.generateKeyPair();
byte[] plaintext = "Hello, Bouncy Castle!".getBytes();
Cipher cipher = Cipher.getInstance("RSA/None/PKCS1Padding", "BC");
cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic());
byte[] ciphertext = cipher.doFinal(plaintext);
System.out.println("Ciphertext: " + new String(ciphertext));
}
}
```
这里只是简单演示了 Bouncy Castle 的一些用法。你可以根据具体的需求,查看 Bouncy Castle 文档并探索更多功能和用法。