【发布时间】:2013-05-07 16:18:09
【问题描述】:
我想使用 java 使用 RSA 公钥加密 DSA 密钥。但是,当我这样做时,我得到了这个错误:
javax.crypto.IllegalBlockSizeException: Data must not be longer than 245 bytes
at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:337)
at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:382)
DSA 和 RSA 密钥大小分别设置为 1024 和 2048。我知道使用 RSA 我们不能加密大小超过 RSA 密钥大小的消息。但是,在这种情况下,DSA 密钥大小小于 RSA 密钥大小。
我猜这个问题与 getEncode() 函数有关,因为当我检查这个函数的返回值时,我知道结果的大小是 335 字节。
我想知道如何解决这个问题? (我不想增加 RSA 的密钥大小)。我将 DSA 密钥大小设置为 1024。为什么 DSA 密钥大小编码后的大小为 335 字节?
DSA和RSA keygen函数以及RSA加密函数如下:
public static KeyPair generateDSAKey() {
KeyPair pair = null;
try {
KeyPairGenerator keyGen = KeyPairGenerator
.getInstance("DSA", "SUN");
SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
keyGen.initialize(1024, random);
pair = keyGen.generateKeyPair();
} catch (Exception e) {
e.printStackTrace();
}
return pair;
}
public static KeyPair generateRSAKey() {
KeyPairGenerator kpg;
KeyPair kp = null;
try {
kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(2048);
kp = kpg.genKeyPair();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return kp;
}
public static byte[] encryptRSA(byte[] msg, PublicKey pubKey) {
byte[] cipherData = null;
try {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
cipherData = cipher.doFinal(msg);
} catch (Exception e) {
e.printStackTrace();
}
return cipherData;
}
我将此函数称为使用 RSA 公钥加密 DSA 密钥:
PrivateKey WSK = Crypto.generateDSAKey().getPrivate();
encWSK = encryptRSA(WSK.getEncoded(), RSAPublicKey);
【问题讨论】:
标签: java encryption rsa dsa