1

这是我的常数

//Encryption fields
/** Algorithm=RSA Mode=ECB Padding=PKCS1Padding*/
public static final String ALGORITHM_MODE_PADDING = "RSA/ECB/PKCS1Padding";
/** Algorithm=RSA */
public static final String ALGORITHM = "RSA";
/** Provider=BouncyCastle */
public static final String PROVIDER = "BC";
/** Key size for the public and private keys */
public static final int KEY_SIZE = 1024;

我已经制作了两个这样的公钥/私钥:

//Generate the keys
KeyPairGenerator kpg = KeyPairGenerator.getInstance(ALGORITHM,PROVIDER);
kpg.initialize(KEY_SIZE);
KeyPair kp = kpg.generateKeyPair();
PublicKey pubk = kp.getPublic();
PrivateKey prvk = kp.getPrivate();

我是这样解密的:

byte[] privateKey = Base64.decodeBase64(pKey); //decode
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKey);
KeyFactory factory = KeyFactory.getInstance(ALGORITHM,PROVIDER);
PrivateKey privKey = factory.generatePrivate(keySpec);
Cipher cipher = Cipher.getInstance(ALGORITHM_MODE_PADDING);
cipher.init(Cipher.ENCRYPT_MODE, privKey);
return cipher.doFinal(data);

这适用于少量数据,当数据变得更大(例如263 字节)时,如果因 IllegalBlockSizeException 而失败。我认为这是因为数据大于 256 字节,但这只是一个猜测,我不知道如何修复它。

我究竟做错了什么?

我将其更改为使用更新方法,但仍然有同样的问题:

// encryption pass
cipher.init(Cipher.ENCRYPT_MODE, privKey);
byte[] cipherText = new byte[cipher.getOutputSize(data.length)];
int ctLength = cipher.update(data, 0, data.length, cipherText, 0);
ctLength += cipher.doFinal(cipherText, ctLength);

顺便说一句,我正在尝试实现数字签名。客户端拥有公钥,服务器拥有私钥。

4

1 回答 1

2

您不能使用 RSA 加密比模数字节大小更多的数据 - 11。可能是您正在寻找的。

于 2010-07-02T19:42:08.113 回答