我一直在尝试理解用于 Java 的 BouncyCaSTLe 加密 API。不幸的是,我发现 Java 密码学通常被服务提供者接口(interface)和行话所掩盖,以至于我无法理解任何东西实际上做了什么。我已经尝试反复阅读必要的文档,但它仍然难以理解,引入了许多远远超出我认为应该需要的概念。
我真正想要的是一个执行以下操作的类:
public class KeyPair {
public byte[] public;
public byte[] private;
}
public class RSACrypto {
public static KeyPair generateRSAKeyPair() { /*implementation*/}
public static byte[] encrypt(byte[] data, byte[] publicKey) { /*impl*/}
public static byte[] decrypt(byte[] encryptedData, byte[] privateKey) { /*impl*/ }
}
抱歉,如果这是一个非常复杂的问题,要问“我真正想要的”。非常欢迎任何关于在哪里阅读 Java 密码学和 BouncyCaSTLe 的指示。非常欢迎任何关于 Java 加密系统实际布局的概述。
最佳答案
import java.security.GeneralSecurityException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import javax.crypto.Cipher;
public class RSACrypto
{
/* A 1024-bit key will encrypt messages up to 117 bytes long. */
private static final int KEY_SIZE = 1024;
private static final String XFORM =
"RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING";
public static KeyPair generateRSAKeyPair()
throws GeneralSecurityException
{
KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
gen.initialize(KEY_SIZE);
return gen.generateKeyPair();
}
public static byte[] encrypt(byte[] plaintext, PublicKey pub)
throws GeneralSecurityException
{
Cipher cipher = Cipher.getInstance(XFORM);
cipher.init(Cipher.ENCRYPT_MODE, pub);
return cipher.doFinal(plaintext);
}
public static byte[] decrypt(byte[] ciphertext, PrivateKey pvt)
throws GeneralSecurityException
{
Cipher cipher = Cipher.getInstance(XFORM);
cipher.init(Cipher.DECRYPT_MODE, pvt);
return cipher.doFinal(ciphertext);
}
public static void main(String... argv)
throws Exception
{
KeyPair pair = RSACrypto.generateRSAKeyPair();
byte[] plaintext = "A short secret message.".getBytes("UTF-8");
byte[] ciphertext = RSACrypto.encrypt(plaintext, pair.getPublic());
byte[] recovered = RSACrypto.decrypt(ciphertext, pair.getPrivate());
System.out.println(new String(recovered, "UTF-8"));
}
}
关于java - 对 Java Security 和 BouncyCaSTLe API 感到茫然和困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/443151/