ECC Encryption and Decryption in Java

南笙酒味 提交于 2019-11-30 16:45:49

In general you are required to perform hybrid encryption with ECC. ECIES for instance is basically a key agreement followed by symmetric encryption. So you cannot directly encrypt anything with ECIES, which is the most common ECC method for encryption. Basically you should couple it to a symmetric cipher. This is actually the best scheme for RSA encryption as well, most of the time.


As you can see you can use this directly as a Cipher using CBC mode & PKCS#7 padding, but beware of the large header (117 bytes for a 384 curve, no less). This is required to perform the key derivation. Make sure that the public key is properly validated (I'm not sure about the Bouncy Castle code in this regards, haven't taken a look at it).

public static void main(String[] args) throws Exception {
    Security.addProvider(new BouncyCastleProvider());

    KeyPairGenerator ecKeyGen = KeyPairGenerator.getInstance("EC", BouncyCastleProvider.PROVIDER_NAME);
    ecKeyGen.initialize(new ECGenParameterSpec("brainpoolP384r1"));

    // doesn't work, which means we are dancing on the leading edge :)
    // KeyPairGenerator ecKeyGen = KeyPairGenerator.getInstance("EC");
    // ecKeyGen.initialize(new ECGenParameterSpec("secp384r1"));

    KeyPair ecKeyPair = ecKeyGen.generateKeyPair();
    System.out.println("What is slow?");

    Cipher iesCipher = Cipher.getInstance("ECIESwithAES");
    iesCipher.init(Cipher.ENCRYPT_MODE, ecKeyPair.getPublic());

    byte[] ciphertext = iesCipher.doFinal(com.google.common.base.Strings.repeat("owlstead", 1000).getBytes());

    iesCipher.init(Cipher.DECRYPT_MODE, ecKeyPair.getPrivate());
    byte[] plaintext = iesCipher.doFinal(ciphertext);

    System.out.println(Hex.toHexString(ciphertext));
    System.out.println(new String(plaintext));
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!