@Test public void testRoundTrip() throws InvalidCipherTextException, IOException { ECPoint pub1 = pub(PRIVATE_KEY1); byte[] plaintext = "Hello world".getBytes(); byte[] ciphertext = encrypt(pub1, plaintext); byte[] plaintext1 = decrypt(PRIVATE_KEY1, ciphertext); assertArrayEquals(plaintext, plaintext1); }
private static byte[] decrypt(BigInteger prv, byte[] cipher) throws InvalidCipherTextException, IOException { ByteArrayInputStream is = new ByteArrayInputStream(cipher); byte[] ephemBytes = new byte[2 * ((curve.getCurve().getFieldSize() + 7) / 8) + 1]; is.read(ephemBytes); ECPoint ephem = curve.getCurve().decodePoint(ephemBytes); byte[] IV = new byte[KEY_SIZE / 8]; is.read(IV); byte[] cipherBody = new byte[is.available()]; is.read(cipherBody); EthereumIESEngine iesEngine = makeIESEngine(false, ephem, prv, IV); return iesEngine.processBlock(cipherBody, 0, cipherBody.length); }
@Test public void testDecryptTestVector() throws IOException, InvalidCipherTextException { byte[] ciphertext = Hex.decode(CIPHERTEXT1); byte[] plaintext = decrypt(PRIVATE_KEY1, ciphertext); assertArrayEquals(new byte[] {1, 1, 1}, plaintext); }
private static byte[] encrypt(ECPoint toPub, byte[] plaintext) throws InvalidCipherTextException, IOException { ECKeyPairGenerator eGen = new ECKeyPairGenerator(); SecureRandom random = new SecureRandom(); KeyGenerationParameters gParam = new ECKeyGenerationParameters(curve, random); eGen.init(gParam); byte[] IV = new byte[KEY_SIZE / 8]; new SecureRandom().nextBytes(IV); AsymmetricCipherKeyPair ephemPair = eGen.generateKeyPair(); BigInteger prv = ((ECPrivateKeyParameters) ephemPair.getPrivate()).getD(); ECPoint pub = ((ECPublicKeyParameters) ephemPair.getPublic()).getQ(); EthereumIESEngine iesEngine = makeIESEngine(true, toPub, prv, IV); ECKeyGenerationParameters keygenParams = new ECKeyGenerationParameters(curve, random); ECKeyPairGenerator generator = new ECKeyPairGenerator(); generator.init(keygenParams); ECKeyPairGenerator gen = new ECKeyPairGenerator(); gen.init(new ECKeyGenerationParameters(ECKey.CURVE, random)); byte[] cipher = iesEngine.processBlock(plaintext, 0, plaintext.length); ByteArrayOutputStream bos = new ByteArrayOutputStream(); bos.write(pub.getEncoded(false)); bos.write(IV); bos.write(cipher); return bos.toByteArray(); }