I want to encrypt the DSA secret key with the RSA public key using java. However, when I do so, I get this error:
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 and RSA key size is set to 1024 and 2048 respectively. I know that using RSA we cannot encrypt messages having size more than the RSA key size. However, in this case, DSA key size is less than RSA key size.
I guess the problem is related to the getEncode() function because when I checked the return value of this function, I understood that the size of result is 335 byte.
I want to know how I can fix this problem? (I do not want to increase RSA the key size). I set DSA key size to 1024. Why DSA key size has the size of 335 byte after encoding?
DSA and RSA keygen functions as well as RSA encryption functions are as follow:
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;
}
and I call this function for encrypting DSA key with RSA public key:
PrivateKey WSK = Crypto.generateDSAKey().getPrivate();
encWSK = encryptRSA(WSK.getEncoded(), RSAPublicKey);