2013-05-13 221 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