这是我的常量
//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);
我正试图实现数字签名。客户端具有公钥,服务器具有私钥。