Write certificate chain to a PEM file - java

I am having a certificate chain where it may contain single certificate or certificate along with intermediate CA's certificate. Now I want to write this into a PEM format file. Is it possible to achieve with existing Java libraries without any third party libraries? Below is my code for certificate chain,
final Collection<? extends Certificate> c =
(Collection<? extends Certificate>) certFactory.generateCertificates(
new ByteArrayInputStream(certificateString.getBytes()));
final Certificate[] certs = (Certificate[]) c.toArray(new Certificate[] {});
How can I write this certs into a PEM file?

try this:
BASE64Encoder encoder = new BASE64Encoder();
out.println(X509Factory.BEGIN_CERT);
encoder.encodeBuffer(cert.getEncoded(), out);
out.println(X509Factory.END_CERT);
or try this
import javax.xml.bind.DatatypeConverter;
x509cert.encode();
try {
System.out.println("---BEGIN CERTIFICATE---");
System.out.println(DatatypeConverter.printBase64Binary(x509cert.getEncoded()));
System.out.println("---END CERTIFICATE---");
} catch (CertificateEncodingException e) {
e.printStackTrace();
}

Related

cert.verify() throws java.security.InvalidKeyException: Supplied key is not a RSAPublicKey instance

I'm trying to check whether a certificate is self-signed.
public static void main(String[] args) throws CertificateException, IOException, GeneralSecurityException
{
// InputStream is = new URL("http://www.d-trust.net/cgi-bin/D-TRUST_Root_CA_2_2021.crt").openStream(); // ok
InputStream is = new URL("http://www.d-trust.net/cgi-bin/D-TRUST_Root_CA_1_2017.crt").openStream(); // not ok
CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate) certFactory.generateCertificate(is);
System.out.println(cert);
System.out.println("Self signed? " + isSelfSigned(cert));
}
public static boolean isSelfSigned(X509Certificate cert) throws GeneralSecurityException
{
try
{
// Try to verify certificate signature with its own public key
PublicKey key = cert.getPublicKey();
System.out.println("key class: " + key.getClass().getName());
System.out.println("Algorithm: " + key.getAlgorithm());
cert.verify(key, new BouncyCastleProvider());
return true;
}
catch (SignatureException | InvalidKeyException ex)
{
// Invalid signature --> not self-signed
ex.printStackTrace();
return false;
}
}
I get this exception in isSelfSigned():
java.security.InvalidKeyException: Supplied key is not a RSAPublicKey instance
at org.bouncycastle.jcajce.provider.asymmetric.rsa.PSSSignatureSpi.engineInitVerify(Unknown Source)
at java.security.Signature$Delegate.engineInitVerify(Signature.java:1168)
at java.security.Signature.initVerify(Signature.java:460)
at sun.security.x509.X509CertImpl.verify(X509CertImpl.java:483)
at NewClass1.isSelfSigned(NewClass1.java:46)
at NewClass1.main(NewClass1.java:35)
This happens only with one of the URLs in my code, not the other one. The problematic certificate has algorithm 1.2.840.113549.1.1.10, which is RSASSA-PSS. I'm using BouncyCastle bcmail-jdk18on 1.72, which also uses bcprov-jdk18on and bcpkix-jdk18on as dependencies.
I'm assuming that this is a self-signed certificate, but of course I don't know for sure.
It turned out to be a java bug. I was using an older jdk8 version, and it runs fine on the current jdk8 version (Amazon Corretto 1.8.0_352). Thanks Topaco for your help.

How to verify X509Certificate with EC key using Bouncy Castle

With Bouncy Castle added as a provider, the following piece of code:
private static boolean isSelfSigned(final X509Certificate cert) {
try {
final PublicKey key = cert.getPublicKey();
cert.verify(key);
return true;
} catch (final RuntimeException re) {
LOG.warn(re, "isSelfSigned: error.");
return false;
} catch (final GeneralSecurityException gse) {
LOG.warn(gse, "isSelfSigned: error.");
return false;
}
}
Results in the following two errors depending on the implementation class of cert:
java.security.InvalidKeyException: Supplied key (org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPublicKey) is not a RSAPublicKey instance
or
java.security.InvalidKeyException: Supplied key (sun.security.ec.ECPublicKeyImpl) is not a RSAPublicKey instance
Does Bouncy Castle not support verifying EC signed certificates? There doesn't appear to be any parameters where I can indicate the keys are not RSA. How do I verify an EC signed certificate using Bouncy Castle?
This was a misunderstanding on my part. The check fails because the certificate does in fact have an EC key, but the parent certificate has an RSA key.

How to authenticate that a plug-in jar was written by same company?

I have an application that needs to run plug-ins written by the same company, but discovered at run-time.
For security, I want the application to authenticate that each plug-in was written by us. No third-party code needs to perform the authentication.
What is an easy way to perform this authentication?
Is it reasonable to get by with challenge-response, or do I need to sign the plug-in jar?
If I need to sign the plug-in jar, what APIs would I use to authenticate?
This is the answer I came to after reading and experimentation.
In this case, a self-signed certificate may be sufficient, since no third-party code needs to authenticate. The hosting code can use the public key to verify the plug-in.
Details
The examples below use the default key algorithm. You may wish to specify a more secure algorithm with -keyalg.
Make the keystore, a public/private key pair, and a self-signed certificate containing the public key
keytool -genkeypair -alias myalias -validity 365 -keystore mykeystore
Validity is measured in days.
Export the certificate containing the public key
keytool -export -keystore mykeystore -alias myalias -file mycertificate.cer
At build time, sign the plug-in jar
jarsigner -keystore mykeystore -signedjar my_signed.jar my_unsigned.jar myalias
At run time, authenticate the plug-in jar contents
This test harness can be used to test the code that follows.
public class CEVerify {
public static void main(String[] args) throws IOException, CertificateException {
File jarFile = new File( "C:\\myplugins\\my_signed.jar" );
String certificatePath = "C:\\mycertificates\\mycertificate.cer";
File certificateFile = new File( certificatePath );
PublicKey publicKey = getPublicKeyFromCertificate( certificateFile );
JarFile jar = new JarFile( jarFile );
boolean isVerified = verify( jar, publicKey );
if ( isVerified ) {
System.out.println( "Verified!" );
}
else {
System.err.println( "NOT verified!" );
}
}
You can extract the public key from the certificate like this:
private static PublicKey
getPublicKeyFromCertificate( File certificateFile )
throws CertificateException, FileNotFoundException
{
CertificateFactory certificateFactory = CertificateFactory.getInstance( "X.509" );
FileInputStream inCertificate = new FileInputStream( certificateFile );
Certificate certificate = certificateFactory.generateCertificate( inCertificate );
return certificate.getPublicKey();
}
Given a jar file and a public key, you can verify appropriate entries in the jar. You may need to exclude other files if you used a different -keyalg, like RSA.
private static boolean
verify( JarFile jar, PublicKey publicKey ) throws IOException {
Enumeration<JarEntry> jarEntries = jar.entries();
while ( jarEntries.hasMoreElements()) {
JarEntry jarEntry = jarEntries.nextElement();
if ( jarEntry.isDirectory()) {
continue;
}
else {
String entryName = jarEntry.getName();
if ( entryName.endsWith( ".SF" ) || entryName.endsWith( ".DSA" )) {
continue;
}
else if ( ! verifyJarEntry( jar, publicKey, jarEntry )) {
return false;
}
}
}
return true;
}
And this authenticates a particular file in a jar. Note the need to read all the bytes in the jar entry before its certificates can be obtained.
private static boolean
verifyJarEntry( JarFile jar, PublicKey publicKey, JarEntry jarEntry)
throws IOException
{
try {
InputStream in = jar.getInputStream( jarEntry );
readAllOf( in );
// public Certificate[] getCertificates()
// ... This method can only be called once the JarEntry has been
// completely verified by reading from the entry input stream
// until the end of the stream has been reached. Otherwise, this
// method will return null.
Certificate[] certificates = jarEntry.getCertificates();
if ((null == certificates) || (0 == certificates.length)) {
return false;
} else {
for (int i = 0; i < certificates.length; ++i) {
Certificate certificate = certificates[i];
try {
certificate.verify( publicKey );
return true;
} catch (Exception e) {
continue;
}
}
return false;
}
} catch (SecurityException e) {
return false;
}
}
Finally, this is the method called above to read all the bytes in a jar entry.
private static void readAllOf(InputStream in) throws IOException {
byte[] buffer = new byte[4096];
while ( 0 < in.read( buffer )) {
continue;
}
}

Using Eclipse To Connect To Network

I want to connect my Eclipse plug-in to an HTTPS URL, but have a problem because the user would need to accept the certificate. Of course there are a couple of tutorials for how to do this in plain Java, but that might be hard to do inside an Eclipse plug-in and I think I'd reinvent the wheel that way.
Because Eclipse has some built in tooling to connect to sites with different network protocols. An example would be the "Install new Software..." action. The tooling even has a preference page that lists HTTPS separately.
According to the Eclipse Help, the KeyStore is used "as a repository for Certificates used for trust decisions [...] when making SSL connections". Yet I couldn't figure out how to use it.
So my question is: How do I use the Eclipse's build in facilities to connect to my HTTPS site?
Based on this answer here I build my own plug-in which loads just the one certificate I need (lucky me) in its EarlyStartup:
public class EarlyStartup implements IStartup {
private static final String ALIAS = "ACME";
#Override
public void earlyStartup() {
final char[] passphrase = "changeit".toCharArray();
final char separator = File.separatorChar;
final File dir = new File(System.getProperty("java.home") + separator + "lib" + separator + "security");
final File file = new File(dir, "cacerts");
try (InputStream certIn = getClass().getResourceAsStream("acme.org.crt");
final InputStream localCertIn = new FileInputStream(file);) {
final KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
keystore.load(localCertIn, passphrase);
if (keystore.containsAlias(ALIAS)) {
return;
}
final CertificateFactory cf = CertificateFactory.getInstance("X.509");
final Certificate cert = cf.generateCertificate(certIn);
keystore.setCertificateEntry(ALIAS, cert);
try (OutputStream out = new FileOutputStream(file)) {
keystore.store(out, passphrase);
}
} catch (final Exception e) {
e.printStackTrace();
}
}
}

Can't find private key from certificate

We are working on encryption-decryption using applet. We find some unexpected issue with digital certificate. One system has certificate and we can't find the private key from that certificate but by installing the same certificate again works fine.
Java Plug-in 10.25.2.17
Using JRE version 1.7.0_25-b17 Java HotSpot(TM) 64-Bit Server VM
User home directory = C:\Users\admin
To access private key we are using below code.
private PrivateKey getPrivateKeyFromKeyStore(String pubkey, KeyStore browser) {
PrivateKey privateKey = null;
String pubKey1 = "";
if (browser != null) {
try {
Field spiField = KeyStore.class.getDeclaredField("keyStoreSpi");
spiField.setAccessible(true);
KeyStoreSpi spi = (KeyStoreSpi) spiField.get(browser);
Field entriesField = spi.getClass().getSuperclass().getDeclaredField("entries");
entriesField.setAccessible(true);
#SuppressWarnings("rawtypes")
Collection entries = (Collection) entriesField.get(spi);
for (Object entry : entries) {
String alias = (String) invokeGetter(entry, "getAlias");
X509Certificate[] certificateChain = (X509Certificate[]) invokeGetter(entry, "getCertificateChain");
for (X509Certificate current : certificateChain) {
pubKey1 = this.bASE64Encoder.encode(current.getPublicKey().getEncoded());
if (pubkey.equals(pubKey1) && !pubkey.equals("")) {
privateKey = (PrivateKey) invokeGetter(entry, "getPrivateKey");
return privateKey;
}
}
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
return privateKey;
}
You won't find private key in certificate because it must be in your keystore, of course, if you generated your cert with its CSR :)
As a tip, I may ask is the cert expired for example?
Anyway, the question is pretty unclear :( If you have cert you must have the keystore which was used to sign your app... It would be better you give more details...

Categories

Resources