Results 1 to 1 of 1
Thread: AES+RSA Wrapping
- 12-11-2011, 12:42 AM #1
Member
- Join Date
- Dec 2011
- Posts
- 1
- Rep Power
- 0
AES+RSA Wrapping
Hi,
I'm trying to use the WRAP.mode to use hybrid encryption. I have the following two functions for encrypting
and decrypting data:
When I use them like this:
I always get the error message:Java Code:byte[] ciphertext = secure.encrypt(plaintextstring.getBytes("UTF-8"), publicKey); byte[] decrypted = secure.decrypt(ciphertext, privateKey);
java.security.InvalidKeyException: Unwrapping failed
Does anybody have an idea what is wrong with the code?
Java Code:public static byte[] encrypt(byte[] plainText, PublicKey publicKey) { byte[] data = null; try { // Create cipher object KeyGenerator keygen = KeyGenerator.getInstance("AES"); SecureRandom random = new SecureRandom(); keygen.init(random); // Initialize with random data SecretKey key = keygen.generateKey(); ByteArrayOutputStream out = new ByteArrayOutputStream(); Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.WRAP_MODE, publicKey); byte[] wrappedKey = cipher.wrap(key); out.write(wrappedKey.length); out.write(wrappedKey); InputStream in = new ByteArrayInputStream(plainText); cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, key); crypt(in, out, cipher); data = out.toByteArray(); in.close(); out.close(); } catch (IOException e) { _logger.warning(e.getMessage()); } catch (GeneralSecurityException e) { _logger.warning(e.getMessage()); } return data; }
Java Code:public static byte[] decrypt(byte[] cipherText, PrivateKey privateKey) { byte[] data = null; try { ByteArrayInputStream in = new ByteArrayInputStream(cipherText); int length = in.read(); byte[] wrappedKey = new byte[length]; in.read(wrappedKey, 0, length); ByteArrayOutputStream out = new ByteArrayOutputStream(); Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.UNWRAP_MODE, privateKey); Key key = cipher.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY); cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, key); crypt(in, out, cipher); data = out.toByteArray(); in.close(); out.close(); } catch (Exception e) { System.out.println(e); } return data; }
Similar Threads
-
Tableviewer Wrapping
By Daniel38 in forum SWT / JFaceReplies: 0Last Post: 02-03-2011, 09:59 AM -
Line Wrapping
By Lil_Aziz1 in forum EclipseReplies: 9Last Post: 06-25-2010, 02:47 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks