Java RSA encrypted AES key - java

I have an RSA private key that I am trying to decrypt another files contents that has an AES key in it. So far all I can seem to get to return from the processes is jargon. Not really sure what I am doing wrong in the below code. I have looked on google and have seen this done at least a 100 different ways.
import java.io.*;
import java.io.IOException;
import java.security.KeyFactory;
import java.security.interfaces.RSAPrivateKey;
import java.security.GeneralSecurityException;
import java.security.spec.PKCS8EncodedKeySpec;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
public class RsaEncryption {
private Cipher _pkCipher;
public RsaEncryption() throws GeneralSecurityException {
// create RSA public key cipher
_pkCipher = Cipher.getInstance("RSA");
}
public String loadKey(File in, String privateKey) throws GeneralSecurityException, IOException, Exception {
privateKey = privateKey.replaceAll("-+.*?-+", "");
byte[] encodedKey = Base64.decodeBase64(privateKey);
// create private key
PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedKey);
KeyFactory kf = KeyFactory.getInstance("RSA");
RSAPrivateKey pk = (RSAPrivateKey) kf.generatePrivate(privateKeySpec);
// read AES key
_pkCipher.init(Cipher.DECRYPT_MODE, pk);
byte[] encryptedBytes = FileUtils.readFileToByteArray(in);
ByteArrayInputStream fileIn = new ByteArrayInputStream(encryptedBytes);
CipherInputStream cis = new CipherInputStream(fileIn, _pkCipher);
DataInputStream dis = new DataInputStream(cis);
byte[] decryptedData = new byte[32];
dis.read(decryptedData);
String key = new String(decryptedData);
return key;
}
}
UPDATE
New way with bouncy castles pem converter still not working
import java.io.StringReader;
import java.io.File;
import java.io.IOException;
import java.security.KeyPair;
import java.security.interfaces.RSAPrivateKey;
import java.security.GeneralSecurityException;
import java.security.interfaces.RSAPublicKey;
import javax.crypto.Cipher;
import org.apache.commons.io.FileUtils;
import org.bouncycastle.openssl.PEMKeyPair;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
public class RsaEncryption {
private Cipher _pkCipher;
private RSAPrivateKey _PrivateKey;
private RSAPublicKey _PublicKey;
public RsaEncryption(String privateKey) throws GeneralSecurityException, IOException {
loadKey(privateKey);
// create RSA public key cipher
_pkCipher = Cipher.getInstance("RSA/None/PKCS1Padding", "BC");
}
private void loadKey(String privateKey) throws IOException {
PEMParser pemParser = new PEMParser(new StringReader(privateKey));
PEMKeyPair pemKeyPair = (PEMKeyPair) pemParser.readObject();
JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
KeyPair keyPair = converter.getKeyPair(pemKeyPair);
_PrivateKey = (RSAPrivateKey) keyPair.getPrivate();
_PublicKey = (RSAPublicKey) keyPair.getPublic();
pemParser.close();
}
public String decrypt(File in) throws GeneralSecurityException , IOException{
_pkCipher.init(Cipher.DECRYPT_MODE, _PrivateKey);
byte[] encryptedBytes = FileUtils.readFileToByteArray(in);
String key = new String(_pkCipher.doFinal(encryptedBytes));
System.out.println(key);
return key;
}
public RSAPrivateKey getPrivateKey() { return _PrivateKey; }
public RSAPublicKey getPublicKey() { return _PublicKey; }
}

RSA can only encrypt a small amount of data which must be processed as a chunk. You don't need a stream for that. Simply call
byte[] aesKey = _pkCipher.doFinal(FileUtils.readFileToByteArray(in));
to get the AES key.

JCE jars where in the wrong directory worked just fine once they got put in the correct directory.

Related

Java: RSA Encryption issue

Small question regarding a Java code for RSA please.
I am having a very simple piece of Java code.
import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;
public class RSA {
public static void main(String[] args) throws Exception {
String privateKeyString = "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAER+iccdhb474gKs6QE9c3JNS3BMlPTyFD2EOP3/NSrBlZtvVpKyQdHxYZ0W6a/IixWc0WjDqqcVAtrwCILmHU7Q==";
String publicKeyString = "MEECAQAwEwYHKoZIzj0CAQYIKoZIzj0DAQcEJzAlAgEBBCCyp0Sx3AgDhXYN3ecGaFYt51dnlrbgJJoRnYMh52QmDg=";
String secretMessage = "My TOP SECRET Message";
byte[] buffer1 = Base64.getDecoder().decode(privateKeyString);
PKCS8EncodedKeySpec keySpec1 = new PKCS8EncodedKeySpec(buffer1);
KeyFactory keyFactory1 = KeyFactory.getInstance("RSA");
PrivateKey privateKey = (RSAPrivateKey) keyFactory1.generatePrivate(keySpec1);
byte[] buffer2 = Base64.getDecoder().decode(publicKeyString);
KeyFactory keyFactory2 = KeyFactory.getInstance("RSA");
PKCS8EncodedKeySpec keySpec2 = new PKCS8EncodedKeySpec(buffer2);
PublicKey publicKey = (RSAPublicKey) keyFactory2.generatePublic(keySpec2);
Cipher encryptCipher = Cipher.getInstance("RSA");
encryptCipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] secretMessageBytes = secretMessage.getBytes(StandardCharsets.UTF_8);
byte[] encryptedMessageBytes = encryptCipher.doFinal(secretMessageBytes);
String encodedMessage = Base64.getEncoder().encodeToString(encryptedMessageBytes);
Cipher decryptCipher = Cipher.getInstance("RSA");
decryptCipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decryptedMessageBytes = decryptCipher.doFinal(encryptedMessageBytes);
String decryptedMessage = new String(decryptedMessageBytes, StandardCharsets.UTF_8);
System.out.println("Step 1" + secretMessage);
System.out.println("Step 2" + encodedMessage);
System.out.println("Step 3" + decryptedMessage);
}
}
I would have expected this to work, and be able to see some kind of gibberish for "Step 2"
But instead, I am seeing this:
Exception in thread "main" java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: IOException : DER input, Integer tag error
at java.base/sun.security.rsa.RSAKeyFactory.engineGeneratePrivate(RSAKeyFactory.java:251)
at java.base/java.security.KeyFactory.generatePrivate(KeyFactory.java:390)
May I ask what is wrong with this piece of code please?
Thank you
In the code there are the following issues:
A private and public EC key are imported (additionally, both keys are swapped). Since RSA encryption is to be performed, RSA keys are to be used instead.
The public key is imported with PKCS8EncodedKeySpec. However, PKCS8EncodedKeySpec is intended for importing a private PKCS#8 key. Since a public X.509/SPKI key is to be imported, X509EncodedKeySpec has to be used instead.
When instantiating the Cipher object, only the algorithm is specified (RSA), but not the padding. Therefore, a provider-dependent default value is used for the padding. To avoid unintentional use of an incorrect padding and cross-platform problems, the padding should also be explicitly specified instead (e.g. RSA/ECB/PKCS1Padding).
The fixed code is as follows:
import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
public class MyClass {
public static void main(String args[]) throws Exception {
// Fix 1: Use RSA keys: The private RSA key is a 2048 bit DER encoded PKCS#8 key (Base64 encoded). The public RSA key is the associated 2048 bit DER encoded X.509/SPKI key (Base64 encoded). Check the RSA keys with an ASN.1 parser, e.g. https://lapo.it/asn1js/.
String privateKeyString = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC6cXloNrocJ8swwj8xktPmEOTfTgJT7KkUwWIGOjBB1QxApgdn5+SUHsakvEJq3Fgn+FnuuN8cfcqWrbT9jURtgNGinJNJ+StPM/PCxfhSv+XbkK11CV2EcJMyDB/8S/9u4E2ht/N1kT4OF2/mVDAq2MjjeUMq8CLmQR63ZMXB8lwmsGJEl4Rwt9WBZNcZFCfuCeBYrKRS7mtLzd4BTXEf0UuiNB/KJrz38TKSI47v/dRbB34wBNn0cuNLHb8t/eDaOvzV6J8SZgOWuL85mng6Fm77QGjUteWgJN76+YhDZgJfsRq1Q67JAy3ZXDHi5X538DcM/o+0wYEqkXxK3iIbAgMBAAECggEASlJj0ExIomKmmBhG8q8SM1s2sWG6gdQMjs6MEeluRT/1c2v79cq2Dum5y/+UBl8x8TUKPKSLpCLs+GXkiVKgHXrFlqoN+OYQArG2EUWzuODwczdYPhhupBXwR3oX4g41k/BsYfQfZBVzBFEJdWrIDLyAUFWNlfdGIj2BTiAoySfyqmamvmW8bsvc8coiGlZ28UC85/Xqx9wOzjeGoRkCH7PcTMlc9F7SxSthwX/k1VBXmNOHa+HzGOgO/W3k1LDqJbq2wKjZTW3iVEg2VodjxgBLMm0MueSGoI6IuaZSPMyFEM3gGvC2+cDBI2SL/amhiTUa/VDlTVw/IKbSuar9uQKBgQDd76M0Po5Lqh8ZhQ3obhFqkfO5EBXy7HUL15cw51kVtwF6Gf/J2HNHjwsg9Nb0eJETTS6bbuVd9bn884JoRS986nVTFNZ4dnjEgKjjQ8GjfzdkpbUxsRLWiIxuOQSpIUZGdMi2ctTTtspvMsDsjRRYdYIQCe/SDsdHGT3vcUCybwKBgQDXDz6iVnY84Fh5iDDVrQOR4lYoxCL/ikCDJjC6y1mjR0eVFdBPQ4j1dDSPU9lahBLby0VyagQCDp/kxQOl0z2zBLRI4I8jUtz9/9KW6ze7U7dQJ7OTfumd5I97OyQOG9XZwKUkRgfyb/PAMBSUSLgosi38f+OC3IN3qlvHFzvxFQKBgQCITpUDEmSczih5qQGIvolN1cRF5j5Ey7t7gXbnXz+Umah7kJpMIvdyfMVOAXJABgi8PQwiBLM0ySXo2LpARjXLV8ilNUggBktYDNktc8DrJMgltayaj3HNd2IglD5rjfc2cKWRgOd7/GlKcHaTEnbreYhfR2sWrWLxJOyoMfuVWwKBgFalCbMV6qU0LfEo8aPlBN8ttVDPVNpntP4h0NgxPXgPK8Pg+gA1UWSy4MouGg/hzkdHaj9ifyLlCX598a5JoT4S0x/ZeVHd/LNI8mtjcRzD6cMde7gdFbpLb5NSjIAyrsIAX4hxvpnqiOYRePkVIz0iLGziiaMbfMwlkrxvm/LRAoGBALPRbtSbE2pPgvOHKHTGPr7gKbmsWVbOcQA8rG801T38W/UPe1XtynMEjzzQ29OaVeQwvUN9+DxFXJ6Yvwj6ih4Wdq109i7Oo1fDnMczOQN9DKch2eNAHrNSOMyLDCBm++wbyHAsS2T0VO8+gzLABviZm5AFCQWfke4LZo5mOS10";
String publicKeyString = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAunF5aDa6HCfLMMI/MZLT5hDk304CU+ypFMFiBjowQdUMQKYHZ+fklB7GpLxCatxYJ/hZ7rjfHH3Klq20/Y1EbYDRopyTSfkrTzPzwsX4Ur/l25CtdQldhHCTMgwf/Ev/buBNobfzdZE+Dhdv5lQwKtjI43lDKvAi5kEet2TFwfJcJrBiRJeEcLfVgWTXGRQn7gngWKykUu5rS83eAU1xH9FLojQfyia89/EykiOO7/3UWwd+MATZ9HLjSx2/Lf3g2jr81eifEmYDlri/OZp4OhZu+0Bo1LXloCTe+vmIQ2YCX7EatUOuyQMt2Vwx4uV+d/A3DP6PtMGBKpF8St4iGwIDAQAB";
String secretMessage = "My TOP SECRET Message";
byte[] buffer1 = Base64.getDecoder().decode(privateKeyString);
PKCS8EncodedKeySpec keySpec1 = new PKCS8EncodedKeySpec(buffer1);
KeyFactory keyFactory1 = KeyFactory.getInstance("RSA");
PrivateKey privateKey = (RSAPrivateKey) keyFactory1.generatePrivate(keySpec1);
byte[] buffer2 = Base64.getDecoder().decode(publicKeyString);
KeyFactory keyFactory2 = KeyFactory.getInstance("RSA");
X509EncodedKeySpec keySpec2 = new X509EncodedKeySpec(buffer2); // Fix 2: Apply X509EncodedKeySpec for the import of the public key
PublicKey publicKey = (RSAPublicKey) keyFactory2.generatePublic(keySpec2);
Cipher encryptCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); // Fix 3: Specify algorithm and padding when instantiating the Cipher object
encryptCipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] secretMessageBytes = secretMessage.getBytes(StandardCharsets.UTF_8);
byte[] encryptedMessageBytes = encryptCipher.doFinal(secretMessageBytes);
String encodedMessage = Base64.getEncoder().encodeToString(encryptedMessageBytes);
Cipher decryptCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); // Fix 3: Specify algorithm and padding when instantiating the Cipher object
decryptCipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decryptedMessageBytes = decryptCipher.doFinal(encryptedMessageBytes);
String decryptedMessage = new String(decryptedMessageBytes, StandardCharsets.UTF_8);
System.out.println("Step 1" + secretMessage);
System.out.println("Step 2" + encodedMessage);
System.out.println("Step 3" + decryptedMessage);
}
}
With these changes, encryption and decryption work.

0auth_signature using SHA1-RSA in java

In have integrated oauth1.0. i am using sha1-rsa signature method. i have generated oauth signature. i got 200 status but i did not get any value in service provider. my doubt is signature generation. how to generate the oauth signature using sha1-rsa in java? i have mentioned link what am using.
`private static KeyPair getKeyPair() throws NoSuchAlgorithmException {
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(1024, new SecureRandom());
return kpg.genKeyPair();
}`
public static String sign(PrivateKey privateKey) throws Exception {
Signature privateSignature = Signature.getInstance(" ");
privateSignature.initSign(privateKey);
//privateSignature.update(plainText.getBytes(UTF_8));
byte[] signature = privateSignature.sign();
System.out.println(Base64.encodeBase64String(signature));
return Base64.encodeBase64String(signature);
//encodeToString(signature);
}
thanks in advance,
Below snippets generate a valid signature, i.e. signs the input data using an RSA Private Key string i.e. creates a private key from contents of a .pkcs8 private key file. This is in Groovy (works with Java with minimal syntax changes:
import java.security.SignatureException;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.Signature;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
//-------- generate RSA-SHA1 signature from request data
def encryptUsingRSASHA1(String data, String key) throws
java.security.SignatureException
{
String result
try {
// get an rsa_sha1 key from the raw key bytes
//SHA1withRSA
Signature signature = Signature.getInstance("SHA1withRSA");
signature.initSign(getPrivateKey(key));
signature.update(data.getBytes("UTF-8"));
byte[] rawRSAsigned = signature.sign();
result= rawRSAsigned.encodeBase64()
} catch (Exception e) {
throw new SignatureException("Failed to generate Signature : " +
e.getMessage());
}
return result
}
//get PrivateKey from key string
def getPrivateKey(String privateKey) throws NoSuchAlgorithmException,
InvalidKeySpecException {
String privateKeyPEM = privateKey.replace("-----BEGIN PRIVATE KEY-----\n",
"").replace("-----END PRIVATE KEY-----", "").replaceAll("\n","");
byte[] privateKeyBytes = privateKeyPEM.decodeBase64();
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePrivate(keySpec);
}

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

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;
}
}

ECDSA Signature Verification Performance in Java

I am trying to calculate the performance of ECDSA signature verification in Java for secp521r1 curve.
I am getting around 3000 signature verification per second.
Adding my other work also, I tested with openssl speed command for secp521r1 curve, there I got around 9000 verification on my machine (40 cores). I tested with Golang also but the performance with secp521r1 is not good, though the performance with secp256r1 is great(28000 verification per second). I reached out to Golang community and found 256 is hand optimized but other curves are not.
I also tested with nodeJs to verify signature, there I got 9000 verification per second which is similar to Openssl. By checking the source code of nodeJs crypto module implementation, I found they are using openssl like implementation.
But I have to work on Java only, so reaching out to the community. Is this the usual result in Java or do we have any openssl like implementation in Java as well?
Dummy Code==========================
package dummy;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.math.BigInteger;
import java.security.InvalidAlgorithmParameterException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Security;
import java.security.Signature;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import org.bouncycastle.asn1.DERInteger;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.io.pem.PemObject;
import org.bouncycastle.util.io.pem.PemReader;
import org.json.JSONObject;
public class DSA {
static JSONObject ob = new JSONObject();
static byte[] strByte = null;
static byte[] realSig;
static String str = "a";//"{\"type\":\"issueTx\",\"userId\":1,\"transaction\":{\"amount\":1000}}"; /a
static byte[] sigdata;
static String sigEdata;
static X509Certificate c;
static String sigTestSigneddata;
public static void main(String[] args)
throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, IOException {
try {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("EC");
keyGen.initialize(new ECGenParameterSpec("secp521r1"), new SecureRandom());
KeyPair pair = keyGen.generateKeyPair();
PrivateKey priv = pair.getPrivate();
PublicKey pub = pair.getPublic();
FileWriter fw = new FileWriter("MyKeys/n.pem");
PemWriter writer = new PemWriter(fw);
writer.writeObject(new PemObject("PUBLIC KEY", pub.getEncoded()));
writer.close();
FileWriter fw2 = new FileWriter("MyKeys/n_sk");
PemWriter writer2 = new PemWriter(fw2);
writer2.writeObject(new PemObject("PRIVATE KEY ", priv.getEncoded()));
writer2.close();
Security.addProvider(new BouncyCastleProvider());
Signature ecdsa;
ecdsa = Signature.getInstance("SHA256withECDSA"); // SHA512WITHECDSA SHA512withECDSA
ecdsa.initSign(getPrivate("MyKeys/n_sk"));
strByte = str.getBytes("UTF-8");
ecdsa.update(strByte);
realSig = ecdsa.sign();
sigEdata = Base64.getEncoder().encodeToString(realSig);
Thread.sleep(1000);
verify();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void verify() throws Exception {
verifySignature();
}
private static void verifySignature() throws Exception {
Signature sig = Signature.getInstance("SHA256withECDSA", "BC"); // SHA256withECDSA // SHA512withECDSA
// sig.initVerify(c.getPublicKey()); to verify using digi cert
sig.initVerify(getPublic("MyKeys/n.pem"));
sig.update(str.getBytes());
System.out.println(sig.verify(Base64.getDecoder().decode(sigEdata)));
// sig.verify(sigEdata.getBytes(Charset.defaultCharset()));
System.out.println(str);
}
private static PrivateKey getPrivate(String filename) throws Exception {
PemReader reader = new PemReader(new FileReader(filename));
PemObject pemObject = reader.readPemObject();
byte[] content = pemObject.getContent();
reader.close();
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(content);
KeyFactory kf = KeyFactory.getInstance("EC");
return kf.generatePrivate(spec);
}
private static PublicKey getPublic(String filename) throws Exception {
PemReader reader = new PemReader(new FileReader(filename));
PemObject pemObject = reader.readPemObject();
byte[] content = pemObject.getContent();
reader.close();
X509EncodedKeySpec spec = new X509EncodedKeySpec(content);
KeyFactory kf = KeyFactory.getInstance("EC");
return kf.generatePublic(spec);
}
}

How to store and reuse keypair in Java?

I am wanting generate a keypair once and reuse it.
public static KeyPair generateKeyPair() throws Exception {
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
generator.initialize(2048, new SecureRandom());
KeyPair pair = generator.generateKeyPair();
return pair;
}
How do I go about this?
There is a bit of a problem here: Java's focus is almost entirely on TLS and the cryptography required to implement TLS. For TLS a private key and a certificate is required. So you get into a situation where you:
have to generate a (bogus) self signed certificate to go with your public key or;
have to find another way of storing the private key without a certificate.
However, with (2.) you quickly get a method that isn't very compatible. If you want to go that way, you could create a PKCS#8 encrypted private key that is encrypted using PBE / CBC.
So here's some code to create a self signed certificate and use that to store the key. Note the expiration date, you could set it to 100 years to be on the safe side (or you could actually do some key management).
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.KeyStore.Entry;
import java.security.KeyStore.PrivateKeyEntry;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.Provider;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Security;
import java.security.UnrecoverableEntryException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Calendar;
import java.util.Date;
import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.cert.X509v3CertificateBuilder;
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.operator.ContentSigner;
import org.bouncycastle.operator.OperatorCreationException;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
public class StoreKeyPair {
public static KeyPair generateKeyPair() throws Exception {
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
generator.initialize(2048, new SecureRandom());
KeyPair pair = generator.generateKeyPair();
return pair;
}
public static Certificate selfSign(KeyPair keyPair, String subjectDN)
throws OperatorCreationException, CertificateException, IOException
{
Provider bcProvider = new BouncyCastleProvider();
Security.addProvider(bcProvider);
long now = System.currentTimeMillis();
Date startDate = new Date(now);
X500Name dnName = new X500Name(subjectDN);
// Using the current timestamp as the certificate serial number
BigInteger certSerialNumber = new BigInteger(Long.toString(now));
Calendar calendar = Calendar.getInstance();
calendar.setTime(startDate);
// 1 Yr validity
calendar.add(Calendar.YEAR, 1);
Date endDate = calendar.getTime();
// Use appropriate signature algorithm based on your keyPair algorithm.
String signatureAlgorithm = "SHA256WithRSA";
SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair
.getPublic().getEncoded());
X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder(dnName,
certSerialNumber, startDate, endDate, dnName, subjectPublicKeyInfo);
ContentSigner contentSigner = new JcaContentSignerBuilder(signatureAlgorithm).setProvider(
bcProvider).build(keyPair.getPrivate());
X509CertificateHolder certificateHolder = certificateBuilder.build(contentSigner);
Certificate selfSignedCert = new JcaX509CertificateConverter()
.getCertificate(certificateHolder);
return selfSignedCert;
}
public static void main(String[] args) throws Exception {
KeyPair generatedKeyPair = generateKeyPair();
String filename = "test_gen_self_signed.pkcs12";
char[] password = "test".toCharArray();
storeToPKCS12(filename, password, generatedKeyPair);
KeyPair retrievedKeyPair = loadFromPKCS12(filename, password);
// you can validate by generating a signature and verifying it or by
// comparing the moduli by first casting to RSAPublicKey, e.g.:
RSAPublicKey pubKey = (RSAPublicKey) generatedKeyPair.getPublic();
RSAPrivateKey privKey = (RSAPrivateKey) retrievedKeyPair.getPrivate();
System.out.println(pubKey.getModulus().equals(privKey.getModulus()));
}
private static KeyPair loadFromPKCS12(String filename, char[] password)
throws KeyStoreException, NoSuchAlgorithmException, CertificateException,
FileNotFoundException, IOException, UnrecoverableEntryException {
KeyStore pkcs12KeyStore = KeyStore.getInstance("PKCS12");
try (FileInputStream fis = new FileInputStream(filename);) {
pkcs12KeyStore.load(fis, password);
}
KeyStore.ProtectionParameter param = new KeyStore.PasswordProtection(password);
Entry entry = pkcs12KeyStore.getEntry("owlstead", param);
if (!(entry instanceof PrivateKeyEntry)) {
throw new KeyStoreException("That's not a private key!");
}
PrivateKeyEntry privKeyEntry = (PrivateKeyEntry) entry;
PublicKey publicKey = privKeyEntry.getCertificate().getPublicKey();
PrivateKey privateKey = privKeyEntry.getPrivateKey();
return new KeyPair(publicKey, privateKey);
}
private static void storeToPKCS12(
String filename, char[] password,
KeyPair generatedKeyPair) throws KeyStoreException, IOException,
NoSuchAlgorithmException, CertificateException, FileNotFoundException,
OperatorCreationException {
Certificate selfSignedCertificate = selfSign(generatedKeyPair, "CN=owlstead");
KeyStore pkcs12KeyStore = KeyStore.getInstance("PKCS12");
pkcs12KeyStore.load(null, null);
KeyStore.Entry entry = new PrivateKeyEntry(generatedKeyPair.getPrivate(),
new Certificate[] { selfSignedCertificate });
KeyStore.ProtectionParameter param = new KeyStore.PasswordProtection(password);
pkcs12KeyStore.setEntry("owlstead", entry, param);
try (FileOutputStream fos = new FileOutputStream(filename)) {
pkcs12KeyStore.store(fos, password);
}
}
}
Note that I was too lazy to properly handle the exceptions.
This code uses a slightly altered version of this answer, see my comments for why I changed the code.
The public key can of course be stored separately as well. Just call getEncoded and store the resulting SubjectPublicKeyInfo structure.

Categories

Resources