2013-05-13 223 views
2

我想使用java对RSA公钥加密DSA私钥。但是,当我这样做时,出现此错误:使用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密钥生成功能,以及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); 

回答

1

一个DSA私钥包含算法参数以及x值。下面是打印到stdout私钥的例子:

Sun DSA Private Key 
parameters: 
    p: 
    fd7f5381 1d751229 52df4a9c 2eece4e7 f611b752 3cef4400 c31e3f80 b6512669 
    455d4022 51fb593d 8d58fabf c5f5ba30 f6cb9b55 6cd7813b 801d346f f26660b7 
    6b9950a5 a49f9fe8 047b1022 c24fbba9 d7feb7c6 1bf83b57 e7c6a8a6 150f04fb 
    83f6d3c5 1ec30235 54135a16 9132f675 f3ae2b61 d72aeff2 2203199d d14801c7 
    q: 
    9760508f 15230bcc b292b982 a2eb840b f0581cf5 
    g: 
    f7e1a085 d69b3dde cbbcab5c 36b857b9 7994afbb fa3aea82 f9574c0b 3d078267 
    5159578e bad4594f e6710710 8180b449 167123e8 4c281613 b7cf0932 8cc8a6e1 
    3c167a8b 547c8d28 e0a3ae1e 2bb3a675 916ea37f 0bfa2135 62f1fb62 7a01243b 
    cca4f1be a8519089 a883dfe1 5ae59f06 928b665e 807b5525 64014c3b fecf492a 

x:  1f853beb d6e30242 cd12bd28 e7055830 22ac43a8 

你可以简单地加密the x value,但它假定您的收件人已经知道算法参数pq

或者您可以发送x值加密和参数未加密(thanks GregS)。

+1

或者他可以加密x值并发送未加密的域参数。 – 2013-05-13 21:19:45