Using BouncyCastle to encrypt with ECIES in Java

后端 未结 1 1917
悲&欢浪女
悲&欢浪女 2021-01-01 05:11

I am trying to encrypt some content using ECC algorithm using BouncyCastle in java. But I am getting exception of BouncyCastle library saying cannot cast JCEECPublicKe

1条回答
  •  [愿得一人]
    2021-01-01 05:58

    Try the following:

    // add instance of provider class
    Security.addProvider(new BouncyCastleProvider());
    
    String name = "secp256r1";
    
    // NOTE just "EC" also seems to work here
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("ECDH", BouncyCastleProvider.PROVIDER_NAME);
    kpg.initialize(new ECGenParameterSpec(name));
    
    // Key pair to store public and private key
    KeyPair keyPair = kpg.generateKeyPair();
    
    Cipher iesCipher = Cipher.getInstance("ECIES", BouncyCastleProvider.PROVIDER_NAME);
    iesCipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic());
    

    And note that in general it is best to keep to JCE classes instead of Bouncy Castle classes when trying to use Bouncy through the JCE. In this case the problem was probably the parameters given to the key generator.

    In above code I used BouncyCastleProvider.PROVIDER_NAME but just "BC" would work equally well of course. Re-instantiating the provider each time is not a good idea, although it should not have influenced the end result.


    Make sure you've got an up to date system to run this code. This code was tested on the following system:

     --- runtime information --- 
    Properties:
        java.vendor                : Oracle Corporation
        java.specification.name    : Java Platform API Specification
        java.specification.version : 1.8
        java.runtime.name          : Java(TM) SE Runtime Environment
        java.runtime.version       : 1.8.0_65-b17
        java.vm.name               : Java HotSpot(TM) 64-Bit Server VM
    Unlimited crypto: yes
     --- info for provider Bouncy Castle --- 
    Bouncy Castle version: 1.520000
    Bouncy Castle provider registered: yes
    

    0 讨论(0)
提交回复
热议问题