如owlstead所述,如果不使用填充进行加密/解密,就不能仅使用“原始”
RSA。一方面,它是非常不安全的;另一方面,Java库甚至不支持它。以下是使用RSA密钥对对AES密钥进行加密/解密的工作代码。
private byte[] EncryptSecretKey (){ Cipher cipher = null; byte[] key = null; try { // initialize the cipher with the user's public key cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.ENCRYPT_MODE, contact.getPublicKey() ); key = cipher.doFinal(skey.getEnpred()); } catch(Exception e ) { System.out.println ( "exception encoding key: " + e.getMessage() ); e.printStackTrace(); } return key;}AES密钥的解密如下所示:
private SecretKey decryptAESKey(byte[] data ){ SecretKey key = null; PrivateKey privKey = null; Cipher cipher = null; try { // this is OUR private key privKey = (PrivateKey)utility.loadLocalKey( Configframe.privateKeyLocation, false); // initialize the cipher... cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.DECRYPT_MODE, privKey ); // generate the aes key! key = new SecretKeySpec ( cipher.doFinal(data), "AES" ); } catch(Exception e) { System.out.println ( "exception decrypting the aes key: " + e.getMessage() ); return null; } return key;}


