I have p7b-file with some certificate inside, I open it in Java and get Subject with this code:
try (InputStream inputStream = new FileInputStream("D:\\test.p7b")) {
final CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
certificateFactory.generateCertificates(inputStream).forEach(certificate -> {
final X509Certificate x509Certificate = (X509Certificate) certificate;
System.out.println("subjectDN: " + x509Certificate.getSubjectDN().getName());
System.out.println("__" + x509Certificate.getExtensionValue("2.5.29.14").hashCode() );
System.out.println("*************************");
});
}
It's work fine, but I need to get Subject Key Identifier like this:
and it must be only on free Java without bouncycastle or any other framework. Please help, how to do it? Thanks!
Related
I have a requirement for slate integration. I have a code for posting data but I want it to convert into java. Below is the code for reference:
'''string host = #url;
string certName = #"myfile.pfx"; // i am having .pem file
string password = #"password"; // no password
var certificate = new System.Security.Cryptography.X509Certificates.X509Certificate2(certName,
password);
System.Net.ServicePointManager.ServerCertificateValidationCallback = (a, b, c, d) => true;
var req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(host);
req.PreAuthenticate = true;
req.Credentials = new System.Net.NetworkCredential("username", "");
req.ClientCertificates.Add(certificate);
req.Method = "POST";
req.ContentType = "text/xml";
string postData = "<hello>world</hello>";
byte[] postBytes = System.Text.Encoding.UTF8.GetBytes(postData);
req.ContentLength = postBytes.Length;
req.GetRequestStream().Write(postBytes, 0, postBytes.Length);
req.GetRequestStream().Close();
var resp = req.GetResponse();'''
Please help in converting c code to java code or in generating a certificate from .pem file. I have checked many links in google but it's not working for me. It is throwing incomplete data or empty data while generating certificate from .pem file.
Thanks in advance,
If you want read the certificate you can use this below java code.
CertificateFactory fact = CertificateFactory.getInstance("X.509");
FileInputStream is = new FileInputStream (pemfilepath);
X509Certificate cer = (X509Certificate) fact.generateCertificate(is);
PublicKey key = cer.getPublicKey();
If you want something else let me know
I have got es-staging.crt file from service provider whose service I am using.
I need to send signed xml with this es-staging.crt certificate. I do not know how to achieve it.
How to solve this in java language?
I have read certificate information by java code, given below.
String cerPath = "E:/configDirectory/es-staging.crt";
fileInputStream = new FileInputStream(new File(cerPath));
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
x509Certificate = (X509Certificate) certificateFactory.generateCertificate(fileInputStream);
publicKey = x509Certificate.getPublicKey();
expiryDate = x509Certificate.getNotAfter();
System.out.println("public key : "+publicKey);
System.out.println("expiryDate : "+expiryDate);
System.out.println("--> Subject: " + x509Certificate.getSubjectDN().getName());
System.out.println("--> Issuer: " + x509Certificate.getIssuerDN().getName());
I have only this es-staging.crt certificate.
You cannot sign a document with an X509 Public Key. You require access to the Private Key.
I am new to Cryptography and so please excuse me if you think this is a basic question
I have a .p7b file which I need to read and extract the individual public certificates i.e the .cer files and store it in the key store. I need not worry about persisting in the key store as there is already a service which takes in the .cer file as byte[] and saves that.
What i want to know is , how do i read the .p7b and extract the individual .cer file? I know that can be done via the openSSL commands, but i need to do the same in java. I need to also read the Issued By name as that will be used as a unique key to persist the certificate.
Thanks in advance
You can get the certificates from a PKCS#7 object with BouncyCastle. Here is a quick code sample:
public Collection<X59Certificate> getCertificates(String path) throws Exception
{
Security.addProvider(new BouncyCastleProvider());
CMSSignedData sd = new CMSSignedData(new FileInputStream(path));
X509Store store = sd.getCertificates("Collection", "BC");
Collection<X509Certificate> certificates = store.getMatches(X509CertStoreSelector.getInstance(new X509CertSelector()));
return certificates;
}
Note that a PKCS#7 may contain more than one certificate. Most of the time it includes intermediate certification authority certificates required to build the certificate chain between the end-user certificate and the root CA.
I was successfully able to read the individual .X509 certificates from the p7b files. Here are the steps
First step includes, getting a byte[] from the java.io.File. The steps include to remove the -----BEGIN PKCS7----- and -----END PKCS7----- from the file, and decode the remaining base64 encoded String.
BufferedReader reader = new BufferedReader(new FileReader(file));
StringBuilder cerfile = new StringBuilder();
String line = null;
while(( line = reader.readLine())!=null){
if(!line.contains("PKCS7")){
cerfile.append(line);
}
}
byte[] fileBytes = Base64.decode(cerfile.toString().getBytes());
The next step is to use the BouncyCastle api to parse the file
CMSSignedData dataParser = new CMSSignedData(trustBundleByte);
ContentInfo contentInfo = dataParser.getContentInfo();
SignedData signedData = SignedData.getInstance(contentInfo.getContent());
CMSSignedData encapInfoBundle = new CMSSignedData(new CMSProcessableByteArray(signedData.getEncapContentInfo().getContent().getDERObject().getEncoded()),contentInfo);
SignedData encapMetaData = SignedData.getInstance(encapInfoBundle.getContentInfo().getContent());
CMSProcessableByteArray cin = new CMSProcessableByteArray(((ASN1OctetString)encapMetaData.getEncapContentInfo().getContent()).getOctets());
CertificateFactory ucf = CertificateFactory.getInstance("X.509");
CMSSignedData unsignedParser = new CMSSignedData(cin.getInputStream());
ContentInfo unsginedEncapInfo = unsignedParser.getContentInfo();
SignedData metaData = SignedData.getInstance(unsginedEncapInfo.getContent());
Enumeration certificates = metaData.getCertificates().getObjects();
// Build certificate path
while (certificates.hasMoreElements()) {
DERObject certObj = (DERObject) certificates.nextElement();
InputStream bin = new ByteArrayInputStream(certObj.getDEREncoded());
X509Certificate cert = (X509Certificate) ucf.generateCertificate(bin);
X500Name x500name = new JcaX509CertificateHolder(cert).getSubject();
RDN cn = x500name.getRDNs(BCStyle.CN)[0];
}
The above steps are working fine, but i am sure there are other solutions with less lines of code to achieve this. I am using bcjdk16 jars.
I need to generate certification chain in my java application becouse its needed when storing privatekey to keystore? Can anybody help me out. I have no idea how to do it..
I need to generate RSA keypair and then store it to keystore. Right now my code looks like this:
public static void main(String[] args)
{
String issuerDN = null;
String addKeyName = "mynewkey";
String delKeyName = null;
String password = "2222";
boolean listStore = true;
boolean deleteKeysAftherWrap = false;
try
{
/* make sure that we have access to the eracom provider */
Provider p = new ERACOMProvider();
Security.addProvider(p);
int keySize = 1024;
KeyPair keyPair = null;
/* get the eracom keystore - access to the adapter */
KeyStore keyStore = KeyStore.getInstance("CRYPTOKI", p.getName());
/* LOAD the keystore from the adapter */
keyStore.load(null, password.toCharArray());
if (addKeyName != null)
{
/* This key cannot be added to the keystore if it already exists */
if (keyStore.containsAlias(addKeyName))
{
println("");
println("Key name already exists");
println("");
}
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", p.getName());
keyPairGenerator.initialize(keySize);
keyPair = keyPairGenerator.generateKeyPair();
PublicKey pubKey = keyPair.getPublic();
PrivateKey privKey = keyPair.getPrivate();
keyStore.setKeyEntry("newpub", pubKey, null, null);
keyStore.setKeyEntry("newpriv", privKey, null, null});
}
the keys are generated but it asks certification chain for storing private key.
And that is the problem right now. How can i generate the certification chain, do i have to generate certifications first, when yes then how?
Not sure what are you trying to achieve, but some time ago I've used this little app (source code included) to insert an existing private key into a keystore. Hopefully you'll find this useful: http://www.agentbob.info/agentbob/79-AB.html
I believe the post http://www.pixelstech.net/article/1406726666-Generate-certificate-in-Java----2 will show you how to generate certificate chain with pure Java. It doesn't require you to use Bouncy Castle.
This post will show you how to generate a certificate chain which has a length longer than 1. While most posts on the Internet will show you creating a certificate chain of length 1 or using BC.
Is there a possibility to generate an java.security.cert.X509Certificate from an byte[]?
Sure.
The certificate objects can be created by an instance of CertificateFactory - in particular, one configured to create X509 certificates. This can be created like so:
CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
Then you need to pass it an InputStream containing the bytes of the certificate. This can be achieved by wrapping your byte array in a ByteArrayInputStream:
InputStream in = new ByteArrayInputStream(bytes);
X509Certificate cert = (X509Certificate)certFactory.generateCertificate(in);
You can do something like:
X509Certificate certificate = signature.getKeyInfo().getX509Datas().get(0).getX509Certificates().get(0);
String lexicalXSDBase64Binary = certificate.getValue();
byte[] decoded = DatatypeConverter.parseBase64Binary(lexicalXSDBase64Binary);
CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
Certificate cert = certFactory.generateCertificate(new ByteArrayInputStream(decoded));
InputStream stream = null;
byte[] bencoded = javax.xml.bind.DatatypeConverter.parseBase64Binary(x509CertificateStr);
try {
CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
cert = (X509Certificate) certFactory.generateCertificate(stream);
} catch (java.security.cert.CertificateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}