// From http://code.calum.org/ public static byte[] encryptSymmetric(byte[] plain, PublicKey publicKey){ byte[] plainZipped = Functions.compressByteArray(plain); long startTime = System.currentTimeMillis(); // System.out.println("encryptSymmetric: plain length is " + plain.length + " bytes"); byte[] raw = null; byte[] encrypted = null; try { // encrypt data with random key KeyGenerator kgen = KeyGenerator.getInstance(Main.SYMMETRIC); kgen.init(Main.SYMMETRICBITS); SecretKey skey = kgen.generateKey(); raw = skey.getEncoded(); SecretKeySpec skeySpec = new SecretKeySpec(raw, Main.SYMMETRIC); Cipher cipher = Cipher.getInstance(Main.SYMMETRIC); cipher.init(Cipher.ENCRYPT_MODE, skeySpec); encrypted = cipher.doFinal(plainZipped); System.out.println("Symmetric encrypted (with " + Main.SYMMETRIC + Main.SYMMETRICBITS + " bits) is " + encrypted.length + " bytes"); } catch (InvalidKeyException ex) { System.err.println(ex.toString()); System.err.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n" + "! If you see this, you've got some problems with your crypto stuff\n" + "! You probably need to install the JCE extensions for strong crypto.\n" + "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); } catch (NoSuchPaddingException ex) { System.err.println(ex.toString()); } catch (NoSuchAlgorithmException ex) { System.err.println(ex.toString()); } catch (IllegalBlockSizeException ex) { System.err.println(ex.toString()); } catch (BadPaddingException ex) { System.err.println(ex.toString()); } // encrypt SecretKey with ASYMMETRIC byte[] encKey = encrypt(raw, publicKey); System.out.println("Encrypted secret key is " + encKey.length + " bytes"); // append encrypted key and encrypted data byte[] ret = Functions.append(encKey, encrypted); //return // System.out.println((System.currentTimeMillis() - startTime ) + " ms elapsed in encryptSymmetric"); // System.out.println("encryptSymmetric: encrypted size is " + ret.length + " bytes"); return ret; }