Click here to Skip to main content
14,691,000 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a public Key text file(.txt) containing a public key. How can I encrypt any input string value using this public key in JAVA?
Kindly guide me in code for reading the public key text file which may be located in any of the drives and then encrypting any string using this public key.
I have written the below code but it is showing an error message:
"java.security.KeyStoreException: RSA not found
Encrypted data:=null"

Kindly help!

What I have tried:

I have tried the following code but I am getting error messages.

import java.security.KeyStore;
import java.security.MessageDigest;
import org.bouncycastle.crypto.params.AsymmetricKeyParameter;
import java.security.PublicKey;
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.BufferedAsymmetricBlockCipher;
import org.bouncycastle.crypto.Digest;
import org.bouncycastle.crypto.AsymmetricBlockCipher;
import org.bouncycastle.crypto.encodings.OAEPEncoding;
import org.bouncycastle.crypto.digests.SHA1Digest;
import org.bouncycastle.crypto.digests.SHA256Digest;
import org.bouncycastle.crypto.engines.RSABlindedEngine;
import org.bouncycastle.crypto.util.PublicKeyFactory;
import java.io.InputStream;
import java.security.cert.X509Certificate;
import java.security.cert.CertificateFactory;
import java.io.FileInputStream;
import java.security.Provider;
import java.security.Security;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import javax.crypto.Cipher;
import java.io.InputStream;
import java.security.*;
//import java.util.Base64;

@SuppressWarnings("unused")
public class Encryption
{
    public String encrypt(final String inputData) {
        String encryptedData = null;
        try {
            Security.addProvider((Provider)new BouncyCastleProvider());
            final FileInputStream fin = new FileInputStream("D:/publickey.txt");
            System.out.println("hello"+fin);
            
            final CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC");
            System.out.println("hello1"+cf);
            KeyStore keyStore = KeyStore.getInstance("RSA");
            
            final java.security.cert.Certificate cert = keyStore.getCertificate("D:/publickey.txt");
            System.out.println("hello2"+cert);
            
            final PublicKey pubkey = cert.getPublicKey();
            final AsymmetricKeyParameter publicKeyParameter = PublicKeyFactory.createKey(pubkey.getEncoded());
            final OAEPEncoding enCryptor = new OAEPEncoding((AsymmetricBlockCipher)new RSABlindedEngine(), (Digest)new SHA256Digest(), (Digest)new SHA1Digest(), (byte[])null);
            final BufferedAsymmetricBlockCipher cipher = new BufferedAsymmetricBlockCipher((AsymmetricBlockCipher)enCryptor);
            cipher.init(true, (CipherParameters)publicKeyParameter);
            cipher.processBytes(inputData.getBytes(), 0, inputData.length());
            encryptedData = Base64.encodeBytes(cipher.doFinal());
        }
        catch (Exception e) {
            System.out.println(e);
        }
        return encryptedData;
    }
    
    public String getSha256(final String value) {
        try {
            final MessageDigest md = MessageDigest.getInstance("SHA-256");
            md.update(value.getBytes());
            return this.bytesToHex(md.digest());
        }
        catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }
    
    private String bytesToHex(final byte[] bytes) {
        final StringBuffer result = new StringBuffer();
        for (final byte b : bytes) {
            result.append(Integer.toString((b & 0xFF) + 256, 16).substring(1));
        }
        return result.toString();
    }
}
Posted
Updated 11-Mar-20 12:00pm
v4
Comments
phil.o 10-Mar-20 15:15pm
   
Please improve your question and provide the error message(s) as well.

1 solution

KeyStore (Java Platform SE 6)[^]

You may try
KeyStore keyStore = KeyStore.getInstance("JKS");
instead.

Or use Security.getProviders()[^] method to have a clue about registered providers on your system.
   
Comments
Knowledge_Seeker 2 7-Apr-20 16:03pm
   
i did not understand your mentioned method--- Security.getProviders() ? Please elaborate!
phil.o 7-Apr-20 16:46pm
   
This static methods returns an array of registered providers on the system.
Put it somewhere in your code, put a breakpoint on its line, start debugging, and watch for returned array.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900