3

有谁知道如何使用 RSA 公钥和私钥加密和解密字符串对象?

我已经使用 KeyPair 生成器在下面创建了私钥和公钥,但我现在想使用公钥来加密数据,并使用私钥来解密它。

public class Keys {

    private static KeyPairGenerator generator;

    private static KeyPair keyPair;

    private static PrivateKey mPrivateKey;

    private static PublicKey mPublicKey;

    private static SecureRandom secureRandom;

    private static final String SHA1PRNG = "SHA1PRNG";

    public static final String RSA = "RSA";

    private Keys() throws NoSuchAlgorithmException {
        generator = KeyPairGenerator.getInstance("RSA");
    }

    /**
     * Generate private and public key pairs
     * 
     * @throws NoSuchAlgorithmException
     */
    private static void generateKeyPair() throws NoSuchAlgorithmException {
        // create SecureRandom object used to generate key pairs

        secureRandom = SecureRandom.getInstance(SHA1PRNG);

        // initialise generator
        generator = KeyPairGenerator.getInstance(RSA);
        generator.initialize(1024, secureRandom);

        // generate keypair using generator
        keyPair = generator.generateKeyPair();

        // asssign private and public keys
        setPrivateKey(keyPair.getPrivate());
        setPublicKey(keyPair.getPublic());

    }

    /**
     * Get private key from key generated
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static PrivateKey getPrivateKey() throws NoSuchAlgorithmException {

        if (mPrivateKey == null) {
            generateKeyPair();
        }
        return mPrivateKey;
    }

    private static void setPrivateKey(PrivateKey privateKey) {
        mPrivateKey = privateKey;
    }

    /**
     * Get public key from key pair generated
     * 
     * @return
     * @throws NoSuchAlgorithmException
     */
    public PublicKey getPublicKey() throws NoSuchAlgorithmException {
        if (mPublicKey == null) {
            generateKeyPair();
        }
        return mPublicKey;
    }

    private static void setPublicKey(PublicKey publicKey) {
        mPublicKey = publicKey;
    }

这是可能的还是加密必须共享和使用相同的密钥?

主要目的是这个。

我将有两个客户端可以相互发送和接收加密数据。

客户端 A 接收加密数据:

客户端 B 请求客户端 A 的公钥。客户端 B 加密字符串并将其发送给客户端 A。客户端 A 收到此加密字符串,然后使用自己的私钥对其进行解密。

如果客户 B 希望接收加密数据,反之亦然。

4

1 回答 1

5

RSA encryption can only be used to encrypt data that is smaller than the modulus of the key. I.e. a 2048-bit RSA public key can only encrypt 256 bytes of data. Some of this data is needed for padding bytes, so typically one is left with even less space to play with.

Commonly this is solved with a hybrid encryption scheme. That is, the data itself is encryption with a temporary symmetric session key, then the session key is encrypted with the recipient's public key. Both the encrypted data and the encrypted session key are sent to the recipient.

You may wish to consider something like OpenPGP, which implements this behaviour (and more). BouncyCastle offesr an OpenPGP implementation for Java.

于 2013-05-20T13:49:40.353 回答