public static byte[] decryptMessage(PrivateKey key, ECIESMessage message) throws ECIESException { try { // check key algorithm if (!key.getAlgorithm().equals(ASYMMETRIC_ALGORITHM)) throw new ECIESException("Wrong key algorithm"); // IES engine IESEngine ies = getIESEngine(); // initialize engine Curve25519DecryptionParameter ep = new Curve25519DecryptionParameter(key.getEncoded(), message.getR()); ParametersWithIV p = new ParametersWithIV(new IESWithCipherParameters(message.getSh1(), message.getSh2(), MAC_KEY_SIZE_BITS, AES_KEY_SIZE_BITS), message.getIv()); ies.init(false, null, ep, p); // decrypt and return data return ies.processBlock(message.getCd(), 0, message.getCd().length); } catch (InvalidCipherTextException ex) { throw new ECIESException("Message corrupted or wrong key", ex); } }
private static ECIESMessage encryptData(PublicKey key, byte[] data, boolean binary, SecureRandom random) throws ECIESException { try { // check key algorithm if (!key.getAlgorithm().equals(ASYMMETRIC_ALGORITHM)) throw new ECIESException("Wrong key algorithm"); // generate shared information byte[] sh1 = new byte[SHARED_INFORMATION_SIZE_BYTES]; random.nextBytes(sh1); byte[] sh2 = new byte[SHARED_INFORMATION_SIZE_BYTES]; random.nextBytes(sh2); byte[] iv = new byte[IV_SIZE_BYTES]; random.nextBytes(iv); // generate R byte[] r = new byte[Curve25519.KEY_SIZE]; random.nextBytes(r); byte[] R = new byte[Curve25519.KEY_SIZE]; Curve25519.curve(R, r, null); // IES engine IESEngine ies = getIESEngine(); // initialize engine Curve25519EncryptionParameter ep = new Curve25519EncryptionParameter(key.getEncoded(), r); ParametersWithIV p = new ParametersWithIV(new IESWithCipherParameters(sh1, sh2, MAC_KEY_SIZE_BITS, AES_KEY_SIZE_BITS), iv); ies.init(true, null, ep, p); // encrypt data byte[] cd = ies.processBlock(data, 0, data.length); // return message return new ECIESMessage(sh1, sh2, iv, R, cd, binary); } catch (InvalidCipherTextException ex) { throw new ECIESException("Message corrupted or wrong key", ex); } }