JAVA API to create a keystore and attaching a csr and keypair to itJava Security: Generate CSR using Java keystore APICreate instance of generic type in Java?How do I create a Java string from the contents of a file?How to create a generic array in Java?Java: Invalid keystore format, when generated through codeHow do I create a file and write to it in Java?Creating a memory leak with JavaHow to Create a Certificate on keystore to my KeyPair?Why reading byte array to an Object throws java.io.StreamCorruptedException?Unsupported record version SSLv2Hello using CloseableHttpClientAndroid KeyStore System - Saving a KeyPair?
Biological Blimps: Propulsion
creating a ":KeepCursor" command
How could a planet have erratic days?
How do you respond to a colleague from another team when they're wrongly expecting that you'll help them?
How do apertures which seem too large to physically fit work?
Terse Method to Swap Lowest for Highest?
Is aluminum electrical wire used on aircraft?
Is there a way to get `mathscr' with lower case letters in pdfLaTeX?
Temporarily disable WLAN internet access for children, but allow it for adults
Why is the "ls" command showing permissions of files in a FAT32 partition?
What if you are holding an Iron Flask with a demon inside and walk into Antimagic Field?
Add big quotation marks inside my colorbox
On a tidally locked planet, would time be quantized?
Open a doc from terminal, but not by its name
Can I still be respawned if I die by falling off the map?
Non-trope happy ending?
Quasinilpotent , non-compact operators
Why does AES have exactly 10 rounds for a 128-bit key, 12 for 192 bits and 14 for a 256-bit key size?
Calculate sum of polynomial roots
What is the evidence for the "tyranny of the majority problem" in a direct democracy context?
Why does a simple loop result in ASYNC_NETWORK_IO waits?
Probability that THHT occurs in a sequence of 10 coin tosses
How does a computer interpret real numbers?
Why Shazam when there is already Superman?
JAVA API to create a keystore and attaching a csr and keypair to it
Java Security: Generate CSR using Java keystore APICreate instance of generic type in Java?How do I create a Java string from the contents of a file?How to create a generic array in Java?Java: Invalid keystore format, when generated through codeHow do I create a file and write to it in Java?Creating a memory leak with JavaHow to Create a Certificate on keystore to my KeyPair?Why reading byte array to an Object throws java.io.StreamCorruptedException?Unsupported record version SSLv2Hello using CloseableHttpClientAndroid KeyStore System - Saving a KeyPair?
I need to attach an existing csr and keypair to a keystore. Given below is an implementation that uses GUI(java swing) to take the input from the user such as keystore name, alias,common name, organization etc.
I try to link the csr to the keystore using keystore.setkeyentry(...), however the keystore is still empty.
I have attached my code below, any help will be very useful:
This code below is used to create a csr
public String getCSR(String cn, String ou, String o, String l,String s) throws Exception
byte[] csr = generatePKCS10(cn, ou, o, l,s,"US");
return new String(csr);
private static byte[] generatePKCS10(String CN, String OU, String O,
String L, String S, String C) throws Exception
// generate PKCS10 certificate request
String sigAlg = "MD5WithRSA";
PKCS10 pkcs10 = new PKCS10(publicKey);
Signature signature = Signature.getInstance(sigAlg);
signature.initSign(privateKey);
// common, orgUnit, org, locality, state, country
X500Principal principal = new X500Principal( "CN=Ole Nordmann, OU=ACME, O=Sales, C=NO");
// pkcs10CertificationRequest kpGen = new PKCS10CertificationRequest(sigAlg, principal, publicKey, null, privateKey);
// byte[] c = kpGen.getEncoded();
X500Name x500name=null;
x500name= new X500Name(principal.getEncoded());
pkcs10.encodeAndSign(x500name, signature);
ByteArrayOutputStream bs = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(bs);
pkcs10.print(ps);
byte[] c = bs.toByteArray();
try
if (ps != null)
ps.close();
if (bs != null)
bs.close();
catch (Throwable th)
return c;
public static X509Certificate generateX509Certificate(String certEntry) throws IOException
InputStream in = null;
X509Certificate cert = null;
try
byte[] certEntryBytes = certEntry.getBytes();
in = new ByteArrayInputStream(certEntryBytes);
CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
cert = (X509Certificate) certFactory.generateCertificate(in);
catch (CertificateException ex)
finally
if (in != null)
in.close();
return cert;
In the main method I do the following to create a keystore and attach it to the csr
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
char[] pass = password.toCharArray();
ks.load(null, pass);
ks.store(fos, pass);
fos.close();
GenerateCSR gcsr = GenerateCSR.getInstance();
System.out.println("Public Key:n"+gcsr.getPublicKey().toString());
System.out.println("Private Key:n"+gcsr.getPrivateKey().toString());
String csr = gcsr.getCSR(CN,OU,O,L,S);
System.out.println("CSR Request Generated!!");
System.out.println(csr);
X509Certificate[] certChain = new X509Certificate[1];
// certChain[0]= gcsr.generateX509Certificate(csr);
X509Certificate myCert = (X509Certificate) CertificateFactory
.getInstance("X509")
.generateCertificate(
// string encoded with default charset
new ByteArrayInputStream(csr.getBytes())
);
certChain[0]= myCert;
ks.setKeyEntry("alias", (Key)gcsr.getPrivateKey(), pass, certChain);
When I check the contents of the keystore, it is empty.
Any advice will be appreciated
Thank You!!!
java security bouncycastle keytool csr
add a comment |
I need to attach an existing csr and keypair to a keystore. Given below is an implementation that uses GUI(java swing) to take the input from the user such as keystore name, alias,common name, organization etc.
I try to link the csr to the keystore using keystore.setkeyentry(...), however the keystore is still empty.
I have attached my code below, any help will be very useful:
This code below is used to create a csr
public String getCSR(String cn, String ou, String o, String l,String s) throws Exception
byte[] csr = generatePKCS10(cn, ou, o, l,s,"US");
return new String(csr);
private static byte[] generatePKCS10(String CN, String OU, String O,
String L, String S, String C) throws Exception
// generate PKCS10 certificate request
String sigAlg = "MD5WithRSA";
PKCS10 pkcs10 = new PKCS10(publicKey);
Signature signature = Signature.getInstance(sigAlg);
signature.initSign(privateKey);
// common, orgUnit, org, locality, state, country
X500Principal principal = new X500Principal( "CN=Ole Nordmann, OU=ACME, O=Sales, C=NO");
// pkcs10CertificationRequest kpGen = new PKCS10CertificationRequest(sigAlg, principal, publicKey, null, privateKey);
// byte[] c = kpGen.getEncoded();
X500Name x500name=null;
x500name= new X500Name(principal.getEncoded());
pkcs10.encodeAndSign(x500name, signature);
ByteArrayOutputStream bs = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(bs);
pkcs10.print(ps);
byte[] c = bs.toByteArray();
try
if (ps != null)
ps.close();
if (bs != null)
bs.close();
catch (Throwable th)
return c;
public static X509Certificate generateX509Certificate(String certEntry) throws IOException
InputStream in = null;
X509Certificate cert = null;
try
byte[] certEntryBytes = certEntry.getBytes();
in = new ByteArrayInputStream(certEntryBytes);
CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
cert = (X509Certificate) certFactory.generateCertificate(in);
catch (CertificateException ex)
finally
if (in != null)
in.close();
return cert;
In the main method I do the following to create a keystore and attach it to the csr
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
char[] pass = password.toCharArray();
ks.load(null, pass);
ks.store(fos, pass);
fos.close();
GenerateCSR gcsr = GenerateCSR.getInstance();
System.out.println("Public Key:n"+gcsr.getPublicKey().toString());
System.out.println("Private Key:n"+gcsr.getPrivateKey().toString());
String csr = gcsr.getCSR(CN,OU,O,L,S);
System.out.println("CSR Request Generated!!");
System.out.println(csr);
X509Certificate[] certChain = new X509Certificate[1];
// certChain[0]= gcsr.generateX509Certificate(csr);
X509Certificate myCert = (X509Certificate) CertificateFactory
.getInstance("X509")
.generateCertificate(
// string encoded with default charset
new ByteArrayInputStream(csr.getBytes())
);
certChain[0]= myCert;
ks.setKeyEntry("alias", (Key)gcsr.getPrivateKey(), pass, certChain);
When I check the contents of the keystore, it is empty.
Any advice will be appreciated
Thank You!!!
java security bouncycastle keytool csr
1
You could probably remove all the import statements from the samples, and remove the GUI pairr entirely, only leaving a sample that generates a keyPair and CSR and that demonstrates how using '.setKeyEntry()' fails to add the key to the store. (That would make answering the question a bit easier :))
– Shastick
Oct 31 '16 at 21:13
Great advice!! Thanks
– user6784240
Nov 1 '16 at 4:32
add a comment |
I need to attach an existing csr and keypair to a keystore. Given below is an implementation that uses GUI(java swing) to take the input from the user such as keystore name, alias,common name, organization etc.
I try to link the csr to the keystore using keystore.setkeyentry(...), however the keystore is still empty.
I have attached my code below, any help will be very useful:
This code below is used to create a csr
public String getCSR(String cn, String ou, String o, String l,String s) throws Exception
byte[] csr = generatePKCS10(cn, ou, o, l,s,"US");
return new String(csr);
private static byte[] generatePKCS10(String CN, String OU, String O,
String L, String S, String C) throws Exception
// generate PKCS10 certificate request
String sigAlg = "MD5WithRSA";
PKCS10 pkcs10 = new PKCS10(publicKey);
Signature signature = Signature.getInstance(sigAlg);
signature.initSign(privateKey);
// common, orgUnit, org, locality, state, country
X500Principal principal = new X500Principal( "CN=Ole Nordmann, OU=ACME, O=Sales, C=NO");
// pkcs10CertificationRequest kpGen = new PKCS10CertificationRequest(sigAlg, principal, publicKey, null, privateKey);
// byte[] c = kpGen.getEncoded();
X500Name x500name=null;
x500name= new X500Name(principal.getEncoded());
pkcs10.encodeAndSign(x500name, signature);
ByteArrayOutputStream bs = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(bs);
pkcs10.print(ps);
byte[] c = bs.toByteArray();
try
if (ps != null)
ps.close();
if (bs != null)
bs.close();
catch (Throwable th)
return c;
public static X509Certificate generateX509Certificate(String certEntry) throws IOException
InputStream in = null;
X509Certificate cert = null;
try
byte[] certEntryBytes = certEntry.getBytes();
in = new ByteArrayInputStream(certEntryBytes);
CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
cert = (X509Certificate) certFactory.generateCertificate(in);
catch (CertificateException ex)
finally
if (in != null)
in.close();
return cert;
In the main method I do the following to create a keystore and attach it to the csr
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
char[] pass = password.toCharArray();
ks.load(null, pass);
ks.store(fos, pass);
fos.close();
GenerateCSR gcsr = GenerateCSR.getInstance();
System.out.println("Public Key:n"+gcsr.getPublicKey().toString());
System.out.println("Private Key:n"+gcsr.getPrivateKey().toString());
String csr = gcsr.getCSR(CN,OU,O,L,S);
System.out.println("CSR Request Generated!!");
System.out.println(csr);
X509Certificate[] certChain = new X509Certificate[1];
// certChain[0]= gcsr.generateX509Certificate(csr);
X509Certificate myCert = (X509Certificate) CertificateFactory
.getInstance("X509")
.generateCertificate(
// string encoded with default charset
new ByteArrayInputStream(csr.getBytes())
);
certChain[0]= myCert;
ks.setKeyEntry("alias", (Key)gcsr.getPrivateKey(), pass, certChain);
When I check the contents of the keystore, it is empty.
Any advice will be appreciated
Thank You!!!
java security bouncycastle keytool csr
I need to attach an existing csr and keypair to a keystore. Given below is an implementation that uses GUI(java swing) to take the input from the user such as keystore name, alias,common name, organization etc.
I try to link the csr to the keystore using keystore.setkeyentry(...), however the keystore is still empty.
I have attached my code below, any help will be very useful:
This code below is used to create a csr
public String getCSR(String cn, String ou, String o, String l,String s) throws Exception
byte[] csr = generatePKCS10(cn, ou, o, l,s,"US");
return new String(csr);
private static byte[] generatePKCS10(String CN, String OU, String O,
String L, String S, String C) throws Exception
// generate PKCS10 certificate request
String sigAlg = "MD5WithRSA";
PKCS10 pkcs10 = new PKCS10(publicKey);
Signature signature = Signature.getInstance(sigAlg);
signature.initSign(privateKey);
// common, orgUnit, org, locality, state, country
X500Principal principal = new X500Principal( "CN=Ole Nordmann, OU=ACME, O=Sales, C=NO");
// pkcs10CertificationRequest kpGen = new PKCS10CertificationRequest(sigAlg, principal, publicKey, null, privateKey);
// byte[] c = kpGen.getEncoded();
X500Name x500name=null;
x500name= new X500Name(principal.getEncoded());
pkcs10.encodeAndSign(x500name, signature);
ByteArrayOutputStream bs = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(bs);
pkcs10.print(ps);
byte[] c = bs.toByteArray();
try
if (ps != null)
ps.close();
if (bs != null)
bs.close();
catch (Throwable th)
return c;
public static X509Certificate generateX509Certificate(String certEntry) throws IOException
InputStream in = null;
X509Certificate cert = null;
try
byte[] certEntryBytes = certEntry.getBytes();
in = new ByteArrayInputStream(certEntryBytes);
CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
cert = (X509Certificate) certFactory.generateCertificate(in);
catch (CertificateException ex)
finally
if (in != null)
in.close();
return cert;
In the main method I do the following to create a keystore and attach it to the csr
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
char[] pass = password.toCharArray();
ks.load(null, pass);
ks.store(fos, pass);
fos.close();
GenerateCSR gcsr = GenerateCSR.getInstance();
System.out.println("Public Key:n"+gcsr.getPublicKey().toString());
System.out.println("Private Key:n"+gcsr.getPrivateKey().toString());
String csr = gcsr.getCSR(CN,OU,O,L,S);
System.out.println("CSR Request Generated!!");
System.out.println(csr);
X509Certificate[] certChain = new X509Certificate[1];
// certChain[0]= gcsr.generateX509Certificate(csr);
X509Certificate myCert = (X509Certificate) CertificateFactory
.getInstance("X509")
.generateCertificate(
// string encoded with default charset
new ByteArrayInputStream(csr.getBytes())
);
certChain[0]= myCert;
ks.setKeyEntry("alias", (Key)gcsr.getPrivateKey(), pass, certChain);
When I check the contents of the keystore, it is empty.
Any advice will be appreciated
Thank You!!!
java security bouncycastle keytool csr
java security bouncycastle keytool csr
edited Nov 1 '16 at 4:32
user6784240
asked Oct 31 '16 at 21:09
user6784240user6784240
11
11
1
You could probably remove all the import statements from the samples, and remove the GUI pairr entirely, only leaving a sample that generates a keyPair and CSR and that demonstrates how using '.setKeyEntry()' fails to add the key to the store. (That would make answering the question a bit easier :))
– Shastick
Oct 31 '16 at 21:13
Great advice!! Thanks
– user6784240
Nov 1 '16 at 4:32
add a comment |
1
You could probably remove all the import statements from the samples, and remove the GUI pairr entirely, only leaving a sample that generates a keyPair and CSR and that demonstrates how using '.setKeyEntry()' fails to add the key to the store. (That would make answering the question a bit easier :))
– Shastick
Oct 31 '16 at 21:13
Great advice!! Thanks
– user6784240
Nov 1 '16 at 4:32
1
1
You could probably remove all the import statements from the samples, and remove the GUI pairr entirely, only leaving a sample that generates a keyPair and CSR and that demonstrates how using '.setKeyEntry()' fails to add the key to the store. (That would make answering the question a bit easier :))
– Shastick
Oct 31 '16 at 21:13
You could probably remove all the import statements from the samples, and remove the GUI pairr entirely, only leaving a sample that generates a keyPair and CSR and that demonstrates how using '.setKeyEntry()' fails to add the key to the store. (That would make answering the question a bit easier :))
– Shastick
Oct 31 '16 at 21:13
Great advice!! Thanks
– user6784240
Nov 1 '16 at 4:32
Great advice!! Thanks
– user6784240
Nov 1 '16 at 4:32
add a comment |
1 Answer
1
active
oldest
votes
You have two main mistakes:
a Certificate Signing Request aka CSR aka PKCS10 is NOT a certificate.
CertificateFactory.generateCertificatewill only read a certificate and not a CSR, and when you provide it with a CSR it throws an exception which your code cleverly suppresses with no indication to anybody there was a serious problem. The commented-out code you had in your earlier revision was closer to that needed to generate a certificate.(if you do create/have a valid certificate)
KeyStore.set*only sets the entry in the in-memory KeyStore object. If you want the keystore contents saved somewhere like in a file after your program exits, you muststoreit AFTER doing the 'set'(s).
Here is your code modified enough it works as I believe you want. Except for trivial formatting and scaffolding, spots I changed are marked by //-- for deletions and //** for additions. Even so I do not recommend it because:
I continue your use of the unsupported
sun.securityclasses, even though you are using BC and it has supported classes for PKCS10 and related bits, plus a CSR is only needed if you want to request a certificate from a CA; to generate a cert yourself just generating the cert directly is easier(less serious) in recent versions of BC pkix has been split to a separate jar and
X509V3CertificateGeneratoris now deprecated in favor ofX509v3CertificateBuilder
//nopackage
import java.io.*;
import java.math.BigInteger;
import java.security.*;
import java.security.cert.*;
import java.util.*;
import javax.security.auth.x500.*;
import org.bouncycastle.jce.X509Principal;
import org.bouncycastle.x509.X509V3CertificateGenerator;
//--import sun.security.pkcs.PKCS10; -- Java7
import sun.security.pkcs10.PKCS10; //** Java8
import sun.security.x509.X500Name;
public class SO40350607GenerateCertIntoKeystoreFile8
public static void main (String[] args) throws Exception
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
//**dummy value for test
KeyPairGenerator kpgen = KeyPairGenerator.getInstance("RSA");
kpgen.initialize(1024); keyPair = kpgen.generateKeyPair();
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
char[] pass = "password".toCharArray();
ks.load(null, pass);
//--ks.store(fos, pass); useless here
//--fos.close();
String csr = new String(generatePKCS10("CommonName","OrgUnit","Org","Locality","State", "US"));
System.out.println("CSR Request Generated!!");
System.out.println(csr);
//--X509Certificate myCert = (X509Certificate) CertificateFactory.getInstance("X509")
//-- .generateCertificate(new ByteArrayInputStream(csr.getBytes()) ); // string encoded with default charset*/
X509Certificate myCert = generateCertificate2 (csr); //**
X509Certificate[] certChain = new X509Certificate[]myCert;
ks.setKeyEntry("alias", keyPair.getPrivate(), pass, certChain);
FileOutputStream fos = new FileOutputStream ("newksfile");
ks.store(fos,pass); fos.close(); //** NOW store to file
private static KeyPair keyPair;
private static byte[] generatePKCS10(String CN, String OU, String O,
String L, String S, String C) throws Exception
// generate PKCS10 certificate request
String sigAlg = "SHA1WithRSA"; //** don't use "MD5WithRSA" even for CSR
PKCS10 pkcs10 = new PKCS10(keyPair.getPublic());
Signature signature = Signature.getInstance(sigAlg);
signature.initSign(keyPair.getPrivate());
// common, orgUnit, org, locality, state, country
//--X500Principal principal = new X500Principal( "CN=Ole Nordmann, OU=ACME, O=Sales, C=NO");
//--X500Name x500name= new X500Name(principal.getEncoded());
//** can do this directly (and better)
X500Name x500name = new X500Name ("CN="+CN+",OU="+OU+",O="+O+",L="+L+",S="+S+",C="+C);
pkcs10.encodeAndSign(x500name, signature);
ByteArrayOutputStream bs = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(bs);
pkcs10.print(ps);
byte[] c = bs.toByteArray();
ps.close(); //** bs,ps are never null, ps.close automatically closes underlying bs,
//** and anyway BAOS doesn't need to be closed (although most streams do)
return c;
//** (whole) routine to generate an actual (though selfsigned) certificate
public static X509Certificate generateCertificate2 (String csrpem) throws Exception
String csrtrim = csrpem.replaceAll("-----[^\n]*\n","").replaceAll("\r?\n","");
//--PKCS10 pkcs10 = new PKCS10 (Base64.decode (csrtrim.toCharArray())); --Java7
PKCS10 pkcs10 = new PKCS10 (Base64.getDecoder().decode (csrtrim.getBytes())); //Java8
// or use the one we had before encoding it -- or the input data directly??
// X509V3CertificateGenerator is deprecated but stay with it for now
X509V3CertificateGenerator cert = new X509V3CertificateGenerator();
cert.setSerialNumber(BigInteger.valueOf(1)); //or generate a random number
cert.setSubjectDN(pkcs10.getSubjectName().asX500Principal());
cert.setIssuerDN(pkcs10.getSubjectName().asX500Principal()); //same since it is self-signed
cert.setPublicKey(pkcs10.getSubjectPublicKeyInfo());
Date now = new Date(); cert.setNotBefore(now);
now.setYear(now.getYear()+1); cert.setNotAfter(now);
cert.setSignatureAlgorithm("SHA1WithRSA");
PrivateKey signingKey = keyPair.getPrivate();
return cert.generate(signingKey, "BC");
Thanks a lot. I have another question - import sun.security.pkcs.PKCS10; does not seem to work. Therefore PKCS10 pkcs10 = new PKCS10 (Base64.decode (csrtrim.toCharArray())); gives an error. Any work around for this problem?
– user6784240
Nov 1 '16 at 17:23
@user6784240: Oops! The IDE where I did this is still on Java7 and on checking 8 I see it moved this class tosun.security.pkcs10-- and also changedjava.util.Base64which I had forgotten wasn't official in 7. Thus confirming my advice about unsupported classes twice! See edit for a minimal fix. But my real recommendation is the comment: you don't need a CSR here at all, instead generate the cert directly from the data that would have been in the CSR.
– dave_thompson_085
Nov 2 '16 at 7:50
Thank you so much!!! This works. The reason I need a CSR is because I need to get it signed from a CA.
– user6784240
Nov 2 '16 at 14:34
1
@user6784240: Your Q didn't say that. You might consider howkeytoolhandles this:-genkeypairgenerates a keypair and selfsigned cert (for that key) and puts them (together) in a keystore;-certrequses keypair and name from keystore to create CSR output to screen or file (not keystore); when you get a cert (and usually chain also) back from a CA,-importcertreplaces the selfsigned cert in the keystore entry with the 'proper' cert chain. ...
– dave_thompson_085
Nov 3 '16 at 11:31
... If you (can) have BC, try the documented (and apparently stable)org.bouncycastle.pkcs.PKCS10CertificationRequestBuilderwith probably (I didn't test) the result oforg.bouncycastle.operator.jcajce.JcaContentSignerBuilder.
– dave_thompson_085
Nov 3 '16 at 11:32
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f40350607%2fjava-api-to-create-a-keystore-and-attaching-a-csr-and-keypair-to-it%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
You have two main mistakes:
a Certificate Signing Request aka CSR aka PKCS10 is NOT a certificate.
CertificateFactory.generateCertificatewill only read a certificate and not a CSR, and when you provide it with a CSR it throws an exception which your code cleverly suppresses with no indication to anybody there was a serious problem. The commented-out code you had in your earlier revision was closer to that needed to generate a certificate.(if you do create/have a valid certificate)
KeyStore.set*only sets the entry in the in-memory KeyStore object. If you want the keystore contents saved somewhere like in a file after your program exits, you muststoreit AFTER doing the 'set'(s).
Here is your code modified enough it works as I believe you want. Except for trivial formatting and scaffolding, spots I changed are marked by //-- for deletions and //** for additions. Even so I do not recommend it because:
I continue your use of the unsupported
sun.securityclasses, even though you are using BC and it has supported classes for PKCS10 and related bits, plus a CSR is only needed if you want to request a certificate from a CA; to generate a cert yourself just generating the cert directly is easier(less serious) in recent versions of BC pkix has been split to a separate jar and
X509V3CertificateGeneratoris now deprecated in favor ofX509v3CertificateBuilder
//nopackage
import java.io.*;
import java.math.BigInteger;
import java.security.*;
import java.security.cert.*;
import java.util.*;
import javax.security.auth.x500.*;
import org.bouncycastle.jce.X509Principal;
import org.bouncycastle.x509.X509V3CertificateGenerator;
//--import sun.security.pkcs.PKCS10; -- Java7
import sun.security.pkcs10.PKCS10; //** Java8
import sun.security.x509.X500Name;
public class SO40350607GenerateCertIntoKeystoreFile8
public static void main (String[] args) throws Exception
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
//**dummy value for test
KeyPairGenerator kpgen = KeyPairGenerator.getInstance("RSA");
kpgen.initialize(1024); keyPair = kpgen.generateKeyPair();
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
char[] pass = "password".toCharArray();
ks.load(null, pass);
//--ks.store(fos, pass); useless here
//--fos.close();
String csr = new String(generatePKCS10("CommonName","OrgUnit","Org","Locality","State", "US"));
System.out.println("CSR Request Generated!!");
System.out.println(csr);
//--X509Certificate myCert = (X509Certificate) CertificateFactory.getInstance("X509")
//-- .generateCertificate(new ByteArrayInputStream(csr.getBytes()) ); // string encoded with default charset*/
X509Certificate myCert = generateCertificate2 (csr); //**
X509Certificate[] certChain = new X509Certificate[]myCert;
ks.setKeyEntry("alias", keyPair.getPrivate(), pass, certChain);
FileOutputStream fos = new FileOutputStream ("newksfile");
ks.store(fos,pass); fos.close(); //** NOW store to file
private static KeyPair keyPair;
private static byte[] generatePKCS10(String CN, String OU, String O,
String L, String S, String C) throws Exception
// generate PKCS10 certificate request
String sigAlg = "SHA1WithRSA"; //** don't use "MD5WithRSA" even for CSR
PKCS10 pkcs10 = new PKCS10(keyPair.getPublic());
Signature signature = Signature.getInstance(sigAlg);
signature.initSign(keyPair.getPrivate());
// common, orgUnit, org, locality, state, country
//--X500Principal principal = new X500Principal( "CN=Ole Nordmann, OU=ACME, O=Sales, C=NO");
//--X500Name x500name= new X500Name(principal.getEncoded());
//** can do this directly (and better)
X500Name x500name = new X500Name ("CN="+CN+",OU="+OU+",O="+O+",L="+L+",S="+S+",C="+C);
pkcs10.encodeAndSign(x500name, signature);
ByteArrayOutputStream bs = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(bs);
pkcs10.print(ps);
byte[] c = bs.toByteArray();
ps.close(); //** bs,ps are never null, ps.close automatically closes underlying bs,
//** and anyway BAOS doesn't need to be closed (although most streams do)
return c;
//** (whole) routine to generate an actual (though selfsigned) certificate
public static X509Certificate generateCertificate2 (String csrpem) throws Exception
String csrtrim = csrpem.replaceAll("-----[^\n]*\n","").replaceAll("\r?\n","");
//--PKCS10 pkcs10 = new PKCS10 (Base64.decode (csrtrim.toCharArray())); --Java7
PKCS10 pkcs10 = new PKCS10 (Base64.getDecoder().decode (csrtrim.getBytes())); //Java8
// or use the one we had before encoding it -- or the input data directly??
// X509V3CertificateGenerator is deprecated but stay with it for now
X509V3CertificateGenerator cert = new X509V3CertificateGenerator();
cert.setSerialNumber(BigInteger.valueOf(1)); //or generate a random number
cert.setSubjectDN(pkcs10.getSubjectName().asX500Principal());
cert.setIssuerDN(pkcs10.getSubjectName().asX500Principal()); //same since it is self-signed
cert.setPublicKey(pkcs10.getSubjectPublicKeyInfo());
Date now = new Date(); cert.setNotBefore(now);
now.setYear(now.getYear()+1); cert.setNotAfter(now);
cert.setSignatureAlgorithm("SHA1WithRSA");
PrivateKey signingKey = keyPair.getPrivate();
return cert.generate(signingKey, "BC");
Thanks a lot. I have another question - import sun.security.pkcs.PKCS10; does not seem to work. Therefore PKCS10 pkcs10 = new PKCS10 (Base64.decode (csrtrim.toCharArray())); gives an error. Any work around for this problem?
– user6784240
Nov 1 '16 at 17:23
@user6784240: Oops! The IDE where I did this is still on Java7 and on checking 8 I see it moved this class tosun.security.pkcs10-- and also changedjava.util.Base64which I had forgotten wasn't official in 7. Thus confirming my advice about unsupported classes twice! See edit for a minimal fix. But my real recommendation is the comment: you don't need a CSR here at all, instead generate the cert directly from the data that would have been in the CSR.
– dave_thompson_085
Nov 2 '16 at 7:50
Thank you so much!!! This works. The reason I need a CSR is because I need to get it signed from a CA.
– user6784240
Nov 2 '16 at 14:34
1
@user6784240: Your Q didn't say that. You might consider howkeytoolhandles this:-genkeypairgenerates a keypair and selfsigned cert (for that key) and puts them (together) in a keystore;-certrequses keypair and name from keystore to create CSR output to screen or file (not keystore); when you get a cert (and usually chain also) back from a CA,-importcertreplaces the selfsigned cert in the keystore entry with the 'proper' cert chain. ...
– dave_thompson_085
Nov 3 '16 at 11:31
... If you (can) have BC, try the documented (and apparently stable)org.bouncycastle.pkcs.PKCS10CertificationRequestBuilderwith probably (I didn't test) the result oforg.bouncycastle.operator.jcajce.JcaContentSignerBuilder.
– dave_thompson_085
Nov 3 '16 at 11:32
add a comment |
You have two main mistakes:
a Certificate Signing Request aka CSR aka PKCS10 is NOT a certificate.
CertificateFactory.generateCertificatewill only read a certificate and not a CSR, and when you provide it with a CSR it throws an exception which your code cleverly suppresses with no indication to anybody there was a serious problem. The commented-out code you had in your earlier revision was closer to that needed to generate a certificate.(if you do create/have a valid certificate)
KeyStore.set*only sets the entry in the in-memory KeyStore object. If you want the keystore contents saved somewhere like in a file after your program exits, you muststoreit AFTER doing the 'set'(s).
Here is your code modified enough it works as I believe you want. Except for trivial formatting and scaffolding, spots I changed are marked by //-- for deletions and //** for additions. Even so I do not recommend it because:
I continue your use of the unsupported
sun.securityclasses, even though you are using BC and it has supported classes for PKCS10 and related bits, plus a CSR is only needed if you want to request a certificate from a CA; to generate a cert yourself just generating the cert directly is easier(less serious) in recent versions of BC pkix has been split to a separate jar and
X509V3CertificateGeneratoris now deprecated in favor ofX509v3CertificateBuilder
//nopackage
import java.io.*;
import java.math.BigInteger;
import java.security.*;
import java.security.cert.*;
import java.util.*;
import javax.security.auth.x500.*;
import org.bouncycastle.jce.X509Principal;
import org.bouncycastle.x509.X509V3CertificateGenerator;
//--import sun.security.pkcs.PKCS10; -- Java7
import sun.security.pkcs10.PKCS10; //** Java8
import sun.security.x509.X500Name;
public class SO40350607GenerateCertIntoKeystoreFile8
public static void main (String[] args) throws Exception
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
//**dummy value for test
KeyPairGenerator kpgen = KeyPairGenerator.getInstance("RSA");
kpgen.initialize(1024); keyPair = kpgen.generateKeyPair();
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
char[] pass = "password".toCharArray();
ks.load(null, pass);
//--ks.store(fos, pass); useless here
//--fos.close();
String csr = new String(generatePKCS10("CommonName","OrgUnit","Org","Locality","State", "US"));
System.out.println("CSR Request Generated!!");
System.out.println(csr);
//--X509Certificate myCert = (X509Certificate) CertificateFactory.getInstance("X509")
//-- .generateCertificate(new ByteArrayInputStream(csr.getBytes()) ); // string encoded with default charset*/
X509Certificate myCert = generateCertificate2 (csr); //**
X509Certificate[] certChain = new X509Certificate[]myCert;
ks.setKeyEntry("alias", keyPair.getPrivate(), pass, certChain);
FileOutputStream fos = new FileOutputStream ("newksfile");
ks.store(fos,pass); fos.close(); //** NOW store to file
private static KeyPair keyPair;
private static byte[] generatePKCS10(String CN, String OU, String O,
String L, String S, String C) throws Exception
// generate PKCS10 certificate request
String sigAlg = "SHA1WithRSA"; //** don't use "MD5WithRSA" even for CSR
PKCS10 pkcs10 = new PKCS10(keyPair.getPublic());
Signature signature = Signature.getInstance(sigAlg);
signature.initSign(keyPair.getPrivate());
// common, orgUnit, org, locality, state, country
//--X500Principal principal = new X500Principal( "CN=Ole Nordmann, OU=ACME, O=Sales, C=NO");
//--X500Name x500name= new X500Name(principal.getEncoded());
//** can do this directly (and better)
X500Name x500name = new X500Name ("CN="+CN+",OU="+OU+",O="+O+",L="+L+",S="+S+",C="+C);
pkcs10.encodeAndSign(x500name, signature);
ByteArrayOutputStream bs = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(bs);
pkcs10.print(ps);
byte[] c = bs.toByteArray();
ps.close(); //** bs,ps are never null, ps.close automatically closes underlying bs,
//** and anyway BAOS doesn't need to be closed (although most streams do)
return c;
//** (whole) routine to generate an actual (though selfsigned) certificate
public static X509Certificate generateCertificate2 (String csrpem) throws Exception
String csrtrim = csrpem.replaceAll("-----[^\n]*\n","").replaceAll("\r?\n","");
//--PKCS10 pkcs10 = new PKCS10 (Base64.decode (csrtrim.toCharArray())); --Java7
PKCS10 pkcs10 = new PKCS10 (Base64.getDecoder().decode (csrtrim.getBytes())); //Java8
// or use the one we had before encoding it -- or the input data directly??
// X509V3CertificateGenerator is deprecated but stay with it for now
X509V3CertificateGenerator cert = new X509V3CertificateGenerator();
cert.setSerialNumber(BigInteger.valueOf(1)); //or generate a random number
cert.setSubjectDN(pkcs10.getSubjectName().asX500Principal());
cert.setIssuerDN(pkcs10.getSubjectName().asX500Principal()); //same since it is self-signed
cert.setPublicKey(pkcs10.getSubjectPublicKeyInfo());
Date now = new Date(); cert.setNotBefore(now);
now.setYear(now.getYear()+1); cert.setNotAfter(now);
cert.setSignatureAlgorithm("SHA1WithRSA");
PrivateKey signingKey = keyPair.getPrivate();
return cert.generate(signingKey, "BC");
Thanks a lot. I have another question - import sun.security.pkcs.PKCS10; does not seem to work. Therefore PKCS10 pkcs10 = new PKCS10 (Base64.decode (csrtrim.toCharArray())); gives an error. Any work around for this problem?
– user6784240
Nov 1 '16 at 17:23
@user6784240: Oops! The IDE where I did this is still on Java7 and on checking 8 I see it moved this class tosun.security.pkcs10-- and also changedjava.util.Base64which I had forgotten wasn't official in 7. Thus confirming my advice about unsupported classes twice! See edit for a minimal fix. But my real recommendation is the comment: you don't need a CSR here at all, instead generate the cert directly from the data that would have been in the CSR.
– dave_thompson_085
Nov 2 '16 at 7:50
Thank you so much!!! This works. The reason I need a CSR is because I need to get it signed from a CA.
– user6784240
Nov 2 '16 at 14:34
1
@user6784240: Your Q didn't say that. You might consider howkeytoolhandles this:-genkeypairgenerates a keypair and selfsigned cert (for that key) and puts them (together) in a keystore;-certrequses keypair and name from keystore to create CSR output to screen or file (not keystore); when you get a cert (and usually chain also) back from a CA,-importcertreplaces the selfsigned cert in the keystore entry with the 'proper' cert chain. ...
– dave_thompson_085
Nov 3 '16 at 11:31
... If you (can) have BC, try the documented (and apparently stable)org.bouncycastle.pkcs.PKCS10CertificationRequestBuilderwith probably (I didn't test) the result oforg.bouncycastle.operator.jcajce.JcaContentSignerBuilder.
– dave_thompson_085
Nov 3 '16 at 11:32
add a comment |
You have two main mistakes:
a Certificate Signing Request aka CSR aka PKCS10 is NOT a certificate.
CertificateFactory.generateCertificatewill only read a certificate and not a CSR, and when you provide it with a CSR it throws an exception which your code cleverly suppresses with no indication to anybody there was a serious problem. The commented-out code you had in your earlier revision was closer to that needed to generate a certificate.(if you do create/have a valid certificate)
KeyStore.set*only sets the entry in the in-memory KeyStore object. If you want the keystore contents saved somewhere like in a file after your program exits, you muststoreit AFTER doing the 'set'(s).
Here is your code modified enough it works as I believe you want. Except for trivial formatting and scaffolding, spots I changed are marked by //-- for deletions and //** for additions. Even so I do not recommend it because:
I continue your use of the unsupported
sun.securityclasses, even though you are using BC and it has supported classes for PKCS10 and related bits, plus a CSR is only needed if you want to request a certificate from a CA; to generate a cert yourself just generating the cert directly is easier(less serious) in recent versions of BC pkix has been split to a separate jar and
X509V3CertificateGeneratoris now deprecated in favor ofX509v3CertificateBuilder
//nopackage
import java.io.*;
import java.math.BigInteger;
import java.security.*;
import java.security.cert.*;
import java.util.*;
import javax.security.auth.x500.*;
import org.bouncycastle.jce.X509Principal;
import org.bouncycastle.x509.X509V3CertificateGenerator;
//--import sun.security.pkcs.PKCS10; -- Java7
import sun.security.pkcs10.PKCS10; //** Java8
import sun.security.x509.X500Name;
public class SO40350607GenerateCertIntoKeystoreFile8
public static void main (String[] args) throws Exception
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
//**dummy value for test
KeyPairGenerator kpgen = KeyPairGenerator.getInstance("RSA");
kpgen.initialize(1024); keyPair = kpgen.generateKeyPair();
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
char[] pass = "password".toCharArray();
ks.load(null, pass);
//--ks.store(fos, pass); useless here
//--fos.close();
String csr = new String(generatePKCS10("CommonName","OrgUnit","Org","Locality","State", "US"));
System.out.println("CSR Request Generated!!");
System.out.println(csr);
//--X509Certificate myCert = (X509Certificate) CertificateFactory.getInstance("X509")
//-- .generateCertificate(new ByteArrayInputStream(csr.getBytes()) ); // string encoded with default charset*/
X509Certificate myCert = generateCertificate2 (csr); //**
X509Certificate[] certChain = new X509Certificate[]myCert;
ks.setKeyEntry("alias", keyPair.getPrivate(), pass, certChain);
FileOutputStream fos = new FileOutputStream ("newksfile");
ks.store(fos,pass); fos.close(); //** NOW store to file
private static KeyPair keyPair;
private static byte[] generatePKCS10(String CN, String OU, String O,
String L, String S, String C) throws Exception
// generate PKCS10 certificate request
String sigAlg = "SHA1WithRSA"; //** don't use "MD5WithRSA" even for CSR
PKCS10 pkcs10 = new PKCS10(keyPair.getPublic());
Signature signature = Signature.getInstance(sigAlg);
signature.initSign(keyPair.getPrivate());
// common, orgUnit, org, locality, state, country
//--X500Principal principal = new X500Principal( "CN=Ole Nordmann, OU=ACME, O=Sales, C=NO");
//--X500Name x500name= new X500Name(principal.getEncoded());
//** can do this directly (and better)
X500Name x500name = new X500Name ("CN="+CN+",OU="+OU+",O="+O+",L="+L+",S="+S+",C="+C);
pkcs10.encodeAndSign(x500name, signature);
ByteArrayOutputStream bs = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(bs);
pkcs10.print(ps);
byte[] c = bs.toByteArray();
ps.close(); //** bs,ps are never null, ps.close automatically closes underlying bs,
//** and anyway BAOS doesn't need to be closed (although most streams do)
return c;
//** (whole) routine to generate an actual (though selfsigned) certificate
public static X509Certificate generateCertificate2 (String csrpem) throws Exception
String csrtrim = csrpem.replaceAll("-----[^\n]*\n","").replaceAll("\r?\n","");
//--PKCS10 pkcs10 = new PKCS10 (Base64.decode (csrtrim.toCharArray())); --Java7
PKCS10 pkcs10 = new PKCS10 (Base64.getDecoder().decode (csrtrim.getBytes())); //Java8
// or use the one we had before encoding it -- or the input data directly??
// X509V3CertificateGenerator is deprecated but stay with it for now
X509V3CertificateGenerator cert = new X509V3CertificateGenerator();
cert.setSerialNumber(BigInteger.valueOf(1)); //or generate a random number
cert.setSubjectDN(pkcs10.getSubjectName().asX500Principal());
cert.setIssuerDN(pkcs10.getSubjectName().asX500Principal()); //same since it is self-signed
cert.setPublicKey(pkcs10.getSubjectPublicKeyInfo());
Date now = new Date(); cert.setNotBefore(now);
now.setYear(now.getYear()+1); cert.setNotAfter(now);
cert.setSignatureAlgorithm("SHA1WithRSA");
PrivateKey signingKey = keyPair.getPrivate();
return cert.generate(signingKey, "BC");
You have two main mistakes:
a Certificate Signing Request aka CSR aka PKCS10 is NOT a certificate.
CertificateFactory.generateCertificatewill only read a certificate and not a CSR, and when you provide it with a CSR it throws an exception which your code cleverly suppresses with no indication to anybody there was a serious problem. The commented-out code you had in your earlier revision was closer to that needed to generate a certificate.(if you do create/have a valid certificate)
KeyStore.set*only sets the entry in the in-memory KeyStore object. If you want the keystore contents saved somewhere like in a file after your program exits, you muststoreit AFTER doing the 'set'(s).
Here is your code modified enough it works as I believe you want. Except for trivial formatting and scaffolding, spots I changed are marked by //-- for deletions and //** for additions. Even so I do not recommend it because:
I continue your use of the unsupported
sun.securityclasses, even though you are using BC and it has supported classes for PKCS10 and related bits, plus a CSR is only needed if you want to request a certificate from a CA; to generate a cert yourself just generating the cert directly is easier(less serious) in recent versions of BC pkix has been split to a separate jar and
X509V3CertificateGeneratoris now deprecated in favor ofX509v3CertificateBuilder
//nopackage
import java.io.*;
import java.math.BigInteger;
import java.security.*;
import java.security.cert.*;
import java.util.*;
import javax.security.auth.x500.*;
import org.bouncycastle.jce.X509Principal;
import org.bouncycastle.x509.X509V3CertificateGenerator;
//--import sun.security.pkcs.PKCS10; -- Java7
import sun.security.pkcs10.PKCS10; //** Java8
import sun.security.x509.X500Name;
public class SO40350607GenerateCertIntoKeystoreFile8
public static void main (String[] args) throws Exception
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
//**dummy value for test
KeyPairGenerator kpgen = KeyPairGenerator.getInstance("RSA");
kpgen.initialize(1024); keyPair = kpgen.generateKeyPair();
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
char[] pass = "password".toCharArray();
ks.load(null, pass);
//--ks.store(fos, pass); useless here
//--fos.close();
String csr = new String(generatePKCS10("CommonName","OrgUnit","Org","Locality","State", "US"));
System.out.println("CSR Request Generated!!");
System.out.println(csr);
//--X509Certificate myCert = (X509Certificate) CertificateFactory.getInstance("X509")
//-- .generateCertificate(new ByteArrayInputStream(csr.getBytes()) ); // string encoded with default charset*/
X509Certificate myCert = generateCertificate2 (csr); //**
X509Certificate[] certChain = new X509Certificate[]myCert;
ks.setKeyEntry("alias", keyPair.getPrivate(), pass, certChain);
FileOutputStream fos = new FileOutputStream ("newksfile");
ks.store(fos,pass); fos.close(); //** NOW store to file
private static KeyPair keyPair;
private static byte[] generatePKCS10(String CN, String OU, String O,
String L, String S, String C) throws Exception
// generate PKCS10 certificate request
String sigAlg = "SHA1WithRSA"; //** don't use "MD5WithRSA" even for CSR
PKCS10 pkcs10 = new PKCS10(keyPair.getPublic());
Signature signature = Signature.getInstance(sigAlg);
signature.initSign(keyPair.getPrivate());
// common, orgUnit, org, locality, state, country
//--X500Principal principal = new X500Principal( "CN=Ole Nordmann, OU=ACME, O=Sales, C=NO");
//--X500Name x500name= new X500Name(principal.getEncoded());
//** can do this directly (and better)
X500Name x500name = new X500Name ("CN="+CN+",OU="+OU+",O="+O+",L="+L+",S="+S+",C="+C);
pkcs10.encodeAndSign(x500name, signature);
ByteArrayOutputStream bs = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(bs);
pkcs10.print(ps);
byte[] c = bs.toByteArray();
ps.close(); //** bs,ps are never null, ps.close automatically closes underlying bs,
//** and anyway BAOS doesn't need to be closed (although most streams do)
return c;
//** (whole) routine to generate an actual (though selfsigned) certificate
public static X509Certificate generateCertificate2 (String csrpem) throws Exception
String csrtrim = csrpem.replaceAll("-----[^\n]*\n","").replaceAll("\r?\n","");
//--PKCS10 pkcs10 = new PKCS10 (Base64.decode (csrtrim.toCharArray())); --Java7
PKCS10 pkcs10 = new PKCS10 (Base64.getDecoder().decode (csrtrim.getBytes())); //Java8
// or use the one we had before encoding it -- or the input data directly??
// X509V3CertificateGenerator is deprecated but stay with it for now
X509V3CertificateGenerator cert = new X509V3CertificateGenerator();
cert.setSerialNumber(BigInteger.valueOf(1)); //or generate a random number
cert.setSubjectDN(pkcs10.getSubjectName().asX500Principal());
cert.setIssuerDN(pkcs10.getSubjectName().asX500Principal()); //same since it is self-signed
cert.setPublicKey(pkcs10.getSubjectPublicKeyInfo());
Date now = new Date(); cert.setNotBefore(now);
now.setYear(now.getYear()+1); cert.setNotAfter(now);
cert.setSignatureAlgorithm("SHA1WithRSA");
PrivateKey signingKey = keyPair.getPrivate();
return cert.generate(signingKey, "BC");
edited Nov 2 '16 at 7:51
answered Nov 1 '16 at 12:47
dave_thompson_085dave_thompson_085
13.7k11633
13.7k11633
Thanks a lot. I have another question - import sun.security.pkcs.PKCS10; does not seem to work. Therefore PKCS10 pkcs10 = new PKCS10 (Base64.decode (csrtrim.toCharArray())); gives an error. Any work around for this problem?
– user6784240
Nov 1 '16 at 17:23
@user6784240: Oops! The IDE where I did this is still on Java7 and on checking 8 I see it moved this class tosun.security.pkcs10-- and also changedjava.util.Base64which I had forgotten wasn't official in 7. Thus confirming my advice about unsupported classes twice! See edit for a minimal fix. But my real recommendation is the comment: you don't need a CSR here at all, instead generate the cert directly from the data that would have been in the CSR.
– dave_thompson_085
Nov 2 '16 at 7:50
Thank you so much!!! This works. The reason I need a CSR is because I need to get it signed from a CA.
– user6784240
Nov 2 '16 at 14:34
1
@user6784240: Your Q didn't say that. You might consider howkeytoolhandles this:-genkeypairgenerates a keypair and selfsigned cert (for that key) and puts them (together) in a keystore;-certrequses keypair and name from keystore to create CSR output to screen or file (not keystore); when you get a cert (and usually chain also) back from a CA,-importcertreplaces the selfsigned cert in the keystore entry with the 'proper' cert chain. ...
– dave_thompson_085
Nov 3 '16 at 11:31
... If you (can) have BC, try the documented (and apparently stable)org.bouncycastle.pkcs.PKCS10CertificationRequestBuilderwith probably (I didn't test) the result oforg.bouncycastle.operator.jcajce.JcaContentSignerBuilder.
– dave_thompson_085
Nov 3 '16 at 11:32
add a comment |
Thanks a lot. I have another question - import sun.security.pkcs.PKCS10; does not seem to work. Therefore PKCS10 pkcs10 = new PKCS10 (Base64.decode (csrtrim.toCharArray())); gives an error. Any work around for this problem?
– user6784240
Nov 1 '16 at 17:23
@user6784240: Oops! The IDE where I did this is still on Java7 and on checking 8 I see it moved this class tosun.security.pkcs10-- and also changedjava.util.Base64which I had forgotten wasn't official in 7. Thus confirming my advice about unsupported classes twice! See edit for a minimal fix. But my real recommendation is the comment: you don't need a CSR here at all, instead generate the cert directly from the data that would have been in the CSR.
– dave_thompson_085
Nov 2 '16 at 7:50
Thank you so much!!! This works. The reason I need a CSR is because I need to get it signed from a CA.
– user6784240
Nov 2 '16 at 14:34
1
@user6784240: Your Q didn't say that. You might consider howkeytoolhandles this:-genkeypairgenerates a keypair and selfsigned cert (for that key) and puts them (together) in a keystore;-certrequses keypair and name from keystore to create CSR output to screen or file (not keystore); when you get a cert (and usually chain also) back from a CA,-importcertreplaces the selfsigned cert in the keystore entry with the 'proper' cert chain. ...
– dave_thompson_085
Nov 3 '16 at 11:31
... If you (can) have BC, try the documented (and apparently stable)org.bouncycastle.pkcs.PKCS10CertificationRequestBuilderwith probably (I didn't test) the result oforg.bouncycastle.operator.jcajce.JcaContentSignerBuilder.
– dave_thompson_085
Nov 3 '16 at 11:32
Thanks a lot. I have another question - import sun.security.pkcs.PKCS10; does not seem to work. Therefore PKCS10 pkcs10 = new PKCS10 (Base64.decode (csrtrim.toCharArray())); gives an error. Any work around for this problem?
– user6784240
Nov 1 '16 at 17:23
Thanks a lot. I have another question - import sun.security.pkcs.PKCS10; does not seem to work. Therefore PKCS10 pkcs10 = new PKCS10 (Base64.decode (csrtrim.toCharArray())); gives an error. Any work around for this problem?
– user6784240
Nov 1 '16 at 17:23
@user6784240: Oops! The IDE where I did this is still on Java7 and on checking 8 I see it moved this class to
sun.security.pkcs10 -- and also changed java.util.Base64 which I had forgotten wasn't official in 7. Thus confirming my advice about unsupported classes twice! See edit for a minimal fix. But my real recommendation is the comment: you don't need a CSR here at all, instead generate the cert directly from the data that would have been in the CSR.– dave_thompson_085
Nov 2 '16 at 7:50
@user6784240: Oops! The IDE where I did this is still on Java7 and on checking 8 I see it moved this class to
sun.security.pkcs10 -- and also changed java.util.Base64 which I had forgotten wasn't official in 7. Thus confirming my advice about unsupported classes twice! See edit for a minimal fix. But my real recommendation is the comment: you don't need a CSR here at all, instead generate the cert directly from the data that would have been in the CSR.– dave_thompson_085
Nov 2 '16 at 7:50
Thank you so much!!! This works. The reason I need a CSR is because I need to get it signed from a CA.
– user6784240
Nov 2 '16 at 14:34
Thank you so much!!! This works. The reason I need a CSR is because I need to get it signed from a CA.
– user6784240
Nov 2 '16 at 14:34
1
1
@user6784240: Your Q didn't say that. You might consider how
keytool handles this: -genkeypair generates a keypair and selfsigned cert (for that key) and puts them (together) in a keystore; -certreq uses keypair and name from keystore to create CSR output to screen or file (not keystore); when you get a cert (and usually chain also) back from a CA, -importcert replaces the selfsigned cert in the keystore entry with the 'proper' cert chain. ...– dave_thompson_085
Nov 3 '16 at 11:31
@user6784240: Your Q didn't say that. You might consider how
keytool handles this: -genkeypair generates a keypair and selfsigned cert (for that key) and puts them (together) in a keystore; -certreq uses keypair and name from keystore to create CSR output to screen or file (not keystore); when you get a cert (and usually chain also) back from a CA, -importcert replaces the selfsigned cert in the keystore entry with the 'proper' cert chain. ...– dave_thompson_085
Nov 3 '16 at 11:31
... If you (can) have BC, try the documented (and apparently stable)
org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder with probably (I didn't test) the result of org.bouncycastle.operator.jcajce.JcaContentSignerBuilder.– dave_thompson_085
Nov 3 '16 at 11:32
... If you (can) have BC, try the documented (and apparently stable)
org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder with probably (I didn't test) the result of org.bouncycastle.operator.jcajce.JcaContentSignerBuilder.– dave_thompson_085
Nov 3 '16 at 11:32
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f40350607%2fjava-api-to-create-a-keystore-and-attaching-a-csr-and-keypair-to-it%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
You could probably remove all the import statements from the samples, and remove the GUI pairr entirely, only leaving a sample that generates a keyPair and CSR and that demonstrates how using '.setKeyEntry()' fails to add the key to the store. (That would make answering the question a bit easier :))
– Shastick
Oct 31 '16 at 21:13
Great advice!! Thanks
– user6784240
Nov 1 '16 at 4:32