开发者

InvalidKeyException while wrapping and unwrapping using RSA algorithm

开发者 https://www.devze.com 2023-03-20 19:32 出处:网络
I am new to Java and want to wrap a symmetric key using RSA algorithm. In my case I am not generating the public key for wrapping, but retrieving the public key from Microsoft Keystore.

I am new to Java and want to wrap a symmetric key using RSA algorithm. In my case I am not generating the public key for wrapping, but retrieving the public key from Microsoft Keystore.

// Encrypt the generated Symmetric AES Key using RSA cipher     
Cipher rsaCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", 
       ks.getProvider().getName()); rsaCipher.init(Cipher.WRAP_MODE, RSAPubKey);
byte[] encryptedSymmKey = rsaCipher.wrap(aeskey);

I am getting an InvalidKeyException as shown below:

Exception in thread "main" java.security.InvalidKeyException: Unsupported key type: Sun RSA public key, 1024 bits
  modulus: 171871587533146191561538456391418351861663300588728159334223437391061141885590024223283480319626015611710315581642512941578588886825766256507714725820048129123720143461110410353346492039350478625370269565346566901446816729164309038944197418238814947654954590754593726047828813400082450341775203029183105860831
  public exponent: 65537
    at sun.security.mscapi.RSACipher.init(RSACipher.java:176)
    at sun.security.mscapi.RSACipher.engineInit(RSACipher.java:129)
    at javax.crypto.Cipher.init(DashoA13*..)
    at javax.crypto.Cipher.init(DashoA13*..)
    at com.sap.srm.crpto.client.applet.CryptoClass.main(CryptoClass.java:102)

Please let me 开发者_运维知识库know if anyone has any suggestion how to use the SunMSCAPI appropriate?


As the error message tells you, you are using a Sun RSA public key. That implies that regardless of how you retrieve the public key (the code is not provided, so I don't know) it is not associated with the MSCAPI key store. My guess is you take the public key from a certificate. So one way to solve your problem is to use the Sun provider Cipher class, too, for wrapping the AES key:

Cipher rsa = Cipher.getInstance("RSA/ECB/PKCS1Padding");
rsaCipher.init(Cipher.WRAP_MODE, RSAPubKey);
byte[] encryptedSymmKey = rsaCipher.wrap(aeskey);

So in this case, there's no need to use the MSCAPI for achieving your goal - you can use the standard providers.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号