0

Is there anyway to encrypt and decrypt a message using Elliptic Curve (EC) Public Key and Private Key using Java?

I was trying to encrypt a message using Elliptic Curve (EC) public key and decrypt it using Elliptic Curve (EC) private key but I keep getting error:

java.security.NoSuchAlgorithmException: Cannot find any provider supporting EC
    at javax.crypto.Cipher.getInstance(Cipher.java:539)
    at encryptanddecrypt.EncryptAndDecrypt.encrypt(EncryptAndDecrypt.java:87)
    at encryptanddecrypt.EncryptAndDecrypt.main(EncryptAndDecrypt.java:48)
BUILD SUCCESSFUL (total time: 0 seconds)

I have try google it but all failed because most of the solution use Encryption and Decryption message using RSA. Can someone help me and advice me what could be the issue over here?

package encryptanddecrypt;

import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.xml.bind.DatatypeConverter;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

public class EncryptAndDecrypt {

    private static final String ALGORITHM = "EC";
    public static void main(String[] args) {
        // TODO code application logic here
        try{
            String publicKeyPem="-----BEGIN PUBLIC KEY-----\n" +
                                "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEQrkzEdm2ClPnfouyeFkCDsjtRC/x\n" +
                                "Iaja7F0RbXn3/qKcYQMinaMIs17OhcJQpxasAi1GAPPqc3yF35ngnrj7Kg==\n" +
                                "-----END PUBLIC KEY-----";
            
            String privateKeyPem="-----BEGIN EC PRIVATE KEY-----\n" +
                                "MHcCAQEEIE3Z7wMD6/dzQ7eij9xHq6PmyJF53Gk91HjYU2RoZgS7oAoGCCqGSM49\n" +
                                "AwEHoUQDQgAEQrkzEdm2ClPnfouyeFkCDsjtRC/xIaja7F0RbXn3/qKcYQMinaMI\n" +
                                "s17OhcJQpxasAi1GAPPqc3yF35ngnrj7Kg==\n" +
                                "-----END EC PRIVATE KEY-----";
            
            byte[] publicKey = convertPublicPem(publicKeyPem);
            byte[] privateKey = convertPrivatePem(privateKeyPem);

            byte[] encryptedData = encrypt(publicKey,"Hi Lingkesh Here".getBytes());

            byte[] decryptedData = decrypt(privateKey, encryptedData);

            System.out.println(new String(decryptedData));
        
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    
    public static byte[] convertPublicPem(String PUBLIC_KEY_STRING){
        
        String publicKeyPEM = PUBLIC_KEY_STRING
                .replace("-----BEGIN PUBLIC KEY-----", "")
                .replaceAll(System.lineSeparator(), "")
                .replace("-----END PUBLIC KEY-----", "");
        byte[] bytes = DatatypeConverter.parseBase64Binary(publicKeyPEM);
        System.out.println(Arrays.toString(bytes));
        return bytes;
    }
    
    public static byte[] convertPrivatePem(String PRIVATE_KEY_STRING){
        
        String privateKeyPEM = PRIVATE_KEY_STRING
                .replace("-----BEGIN EC PRIVATE KEY-----", "")
                .replaceAll(System.lineSeparator(), "")
                .replace("-----END EC PRIVATE KEY-----", "");
        byte[] bytes = DatatypeConverter.parseBase64Binary(privateKeyPEM);
        System.out.println(Arrays.toString(bytes));
        return bytes;
    }
    
    public static byte[] encrypt(byte[] publicKey, byte[] inputData)
            throws Exception {

        PublicKey key = KeyFactory.getInstance(ALGORITHM)
                .generatePublic(new X509EncodedKeySpec(publicKey));

        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, key);

        byte[] encryptedBytes = cipher.doFinal(inputData);

        return encryptedBytes;
    }

    public static byte[] decrypt(byte[] privateKey, byte[] inputData)
            throws Exception {

        PrivateKey key = KeyFactory.getInstance(ALGORITHM)
                .generatePrivate(new PKCS8EncodedKeySpec(privateKey));

        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, key);

        byte[] decryptedBytes = cipher.doFinal(inputData);

        return decryptedBytes;
    }
    
       public static KeyPair generateKeyPair()
            throws NoSuchAlgorithmException, NoSuchProviderException {

        KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM);

        SecureRandom random = SecureRandom.getInstance("SHA256PRNG", "SUN");

        keyGen.initialize(256, random);

        KeyPair generateKeyPair = keyGen.generateKeyPair();
        return generateKeyPair;
    }
    
}
  • The error message says there's no Elliptic Curve (EC) encryption / decryption function. You have to use a different encryption / decryption algorithm. – Gilbert Le Blanc Apr 23 '21 at 11:14
  • This [Stack Overflow question](https://stackoverflow.com/questions/43433930/encryption-and-decryption-of-text-messages-using-elliptic-curve-cryptography-sep) discusses writing your own Elliptic Curve code. – Gilbert Le Blanc Apr 23 '21 at 11:17
  • 2
    You could use a library like Bouncy Castle and run an ECIES encryption but you should be aware that (pure) asymmetric encryption schemes are limited in the amount of data they can encrypt so mostly we talk about **hybrid encryption**. – Michael Fehr Apr 23 '21 at 20:50

0 Answers0