Reading certificate error - java

I am getting the following exception when running my application in a different server. The code works in two different tomcat servers, but on a specific one it doesn't work.
java.lang.NoClassDefFoundError:
org/bouncycastle/asn1/pkcs/PrivateKeyInfo
org.bouncycastle.jcajce.provider.asymmetric.rsa.KeyFactorySpi.engineGeneratePrivate(Unknown
Source) java.security.KeyFactory.generatePrivate(KeyFactory.java:372)
The part of the code when I am getting the error is the following on this line
> pk = kf.generatePrivate(ks);
PrivateKey pk = null;
X509Certificate cert = null;
Security.addProvider(new BouncyCastleProvider());
try{
byte [] key = Base64.decodeBase64(llave.getBytes());
byte [] cer = Base64.decodeBase64(certificado.getBytes());
KeyFactory kf = KeyFactory.getInstance("RSA");
PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(key);
pk = kf.generatePrivate(ks);
pk.getEncoded();
CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
InputStream in = new ByteArrayInputStream(cer);
cert = (X509Certificate)certFactory.generateCertificate(in);
DateTime fechaDesde = new DateTime(cert.getNotBefore());
DateTime fechaHasta = new DateTime(cert.getNotAfter());
Does somebody knows why this happens?

java.lang.NoClassDefFoundError This exception is thrown when JVM is unable to find a particular class at runtime which was available during compile time.
This link will help you

Related

Error with BouncyCastle library 1.59 (NoSuchAlgorithmException)

I have updated BouncyCastle library 1.49 to version 1.59 and I am getting the following error:
exception unwrapping private key - java.security.NoSuchAlgorithmException: Cannot find any provider supporting 2.16.840.1.101.3.4.1.42
java.io.IOException: exception unwrapping private key - java.security.NoSuchAlgorithmException: Cannot find any provider supporting 2.16.840.1.101.3.4.1.42
at org.bouncycastle.jcajce.provider.keystore.pkcs12.PKCS12KeyStoreSpi.unwrapKey(Unknown Source)
at org.bouncycastle.jcajce.provider.keystore.pkcs12.PKCS12KeyStoreSpi.engineLoad(Unknown Source)
at java.security.KeyStore.load(KeyStore.java:1226)
The code implemented is as follows:
KeyStore keystore = KeyStore.getInstance("PKCS12", new BouncyCastleProvider());
keystore.load(new ByteArrayInputStream(hexStringToByteArray(privKey)), passphrase.toCharArray());
Enumeration<String> aliases = keystore.aliases();
String keyAlias = "";
while (aliases.hasMoreElements()) {
keyAlias = (String) aliases.nextElement();
}
PrivateKey key = (PrivateKey) keystore.getKey(keyAlias, passphrase.toCharArray());
final Cipher cipher = Cipher.getInstance("RSA/NONE/OAEPWithSHA256AndMGF1Padding", new BouncyCastleProvider());
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] arr = hexStringToByteArray(encriptedPin);
byte[] decryptedTextBytes = cipher.doFinal(arr);
return new String(decryptedTextBytes);
I have updated JCE Policy and it still does not work, as well as the .pk8 certificate.
Has anyone had this problem? Any additional information tell me.
Thanks in advance,
Regards.

The system cannot find the file specified trying to create .jks file

I'm currently learning encryption/decryption techniques in Java and one major problem I have come across is storing the key in a .jks file and being able to load it in during different launches. In my calling class it calls the constructor and this is the code for it:
public Encrypt_Decrypt() throws NoSuchAlgorithmException, NoSuchPaddingException
{
Cipher cipher = Cipher.getInstance("AES");
SecureRandom randomSecureRandom = SecureRandom.getInstance("SHA1PRNG");
byte[] iv = new byte[cipher.getBlockSize()];
randomSecureRandom.nextBytes(iv);
IvParameterSpec ivParams = new IvParameterSpec(iv);
ivSpec = ivParams;
SecretKey secretKey = KeyGenerator.getInstance("AES").generateKey();
byte[] keyBytes = secretKey.getEncoded();
SecretKeySpec sks = new SecretKeySpec(keyBytes, "AES");
key = sks;
KeyStore.SecretKeyEntry entry = new KeyStore.SecretKeyEntry(key);
KeyStore.ProtectionParameter protParam = new KeyStore.PasswordProtection("password".toCharArray());
try
{
File f = new File("keystore.jks");
KeyStore keyStore = KeyStore.getInstance("JKS");
java.io.FileInputStream fis = null;
try
{
fis = new java.io.FileInputStream("keystore");
}
finally
{
if (fis != null)
{
fis.close();
}
}
keyStore.load(fis, "password".toCharArray());
keyStore.setEntry("key", entry, protParam);
try (FileOutputStream fout = new FileOutputStream(f))
{
keyStore.store(fout, "password".toCharArray());
;
}
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}
After launching this code in the calling class, this is the error it returns:
keystore (The system cannot find the file specified)
In my code I create the file so why is it having an issue? I looked in my project folder and it is not being saved there so what do I have to do to be able to create, store and use this file without issues?
The keystore (The system cannot find the file specified) message relates to this line:
new java.io.FileInputStream("keystore");
It looks like that should have been using the File f? Something similar to how the FileOutputStream is handled just below works well:
try (FileInputStream fis = new FileInputStream(f)) {
keyStore.load(fis, "password".toCharArray());
}
For reference, there's another error waiting there. Trying to store the AES symmetric key in the JKS keystore results in this error:
java.security.KeyStoreException: Cannot store non-PrivateKeys
at sun.security.provider.JavaKeyStore.engineSetKeyEntry(JavaKeyStore.java:258)
at sun.security.provider.JavaKeyStore$JKS.engineSetKeyEntry(JavaKeyStore.java:56)
at java.security.KeyStoreSpi.engineSetEntry(KeyStoreSpi.java:550)
at sun.security.provider.KeyStoreDelegator.engineSetEntry(KeyStoreDelegator.java:179)
at sun.security.provider.JavaKeyStore$DualFormatJKS.engineSetEntry(JavaKeyStore.java:70)
at java.security.KeyStore.setEntry(KeyStore.java:1557)
at KeystoreTest.main(KeystoreTest.java:44)
This is because the JKS storetype only supports public/private keys - also here.
With a new JCEKS keystore instead, your example code then worked fine:
File f = new File("keystore.jceks");
KeyStore keyStore = KeyStore.getInstance("JCEKS");

NullPointerException in BouncyCastleProvider while creating X509Certificate

I'm creating X509Certificate from bytes, but that is throwing NullPointerException, In my application I'm doing two way(Step one getting Signature data in Bytes stored into DB, later i fetched from DB), both are consolidate in one shot, Getting exception in last line(System.out.println)
public static void main(String[] args) throws Exception {
File file = new File("C://connect.cer");
InputStream input = new FileInputStream(file);
Security.addProvider(new BouncyCastleProvider());
CertificateFactory certFactory = CertificateFactory.getInstance("X.509", "BC");
X509Certificate cert = (X509Certificate) certFactory.generateCertificate(input);
byte[] certBytes = cert.getSignature();
System.out.println("IssuerDN Name>>>>>>>>>>>>>>"+cert.getIssuerDN().getName()+">>>>>>>>>>>>>>");
InputStream input2 = new ByteArrayInputStream(certBytes);
CertificateFactory certFactory2 = CertificateFactory.getInstance("X.509", "BC");
X509Certificate cert2 = (X509Certificate) certFactory2.generateCertificate(input2);
System.out.println("IssuerDN Name>>>>>>>>>>>>>>"+cert2.getIssuerDN().getName()+">>>>>>>>>>>>>>");
}
Instead of cert.getSignature() i used cert.getEncoded(), It is forking fine.

How to access certificate from eToken in java

I want to read certificate from eToken when it plugged-in, when I store that certificate on local machine I can read it through my java application but, I don't know how to read it from eToken.
RSAPublicKey pub;
String fileName = "C:\\myCert.cer";
InputStream inStream = new FileInputStream(fileName);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
X509Certificate cert =
(X509Certificate)cf.generateCertificate(inStream);
inStream.close();
pub = (RSAPublicKey) cert.getPublicKey();
System.out.println(cert.getIssuerDN());
System.out.println(cert.getSubjectDN());
System.out.println(cert.getSubjectAlternativeNames());
byte [] tempPub = pub.getEncoded();
String sPub = new String( tempPub );
One way to do this is by using the PKCS#11 provider. It comes with examples, too.

Obtaining public key from certificate

I'm trying to obtain the public key of a Certificate using the method:
FileInputStream fin = new FileInputStream("PathToCertificate");
CertificateFactory f = CertificateFactory.getInstance("X.509");
X509Certificate certificate = (X509Certificate)f.generateCertificate(fin);
PublicKey pk = certificate.getPublicKey();
but I receive the following error:
Exception in thread "main" java.lang.ClassCastException: sun.security.x509.X509CertImpl cannot be cast to codec.x509.X509Certificate
at sergas_testcertificates.Main.main(Main.java:54)
Does anyone know what this error is about?
Thanks in advance
You have the wrong class imported for X509Certificate.
You are likely looking for java.security.cert.X509Certificate not codec.x509.X509Certificate.
X509Certificate certificate = (X509Certificate)f.generateCertificate(fin);
PublicKey pk = certificate.getPublicKey();
since you are only pulling the public key, you can use the certificate class. The factory class will decide what type of a certificate to return.
Certificate certificate = f.generateCertificate(fin);
PublicKey pk = certificate.getPublicKey();
If you need to cast this for antoher reason, check your imports and change it, X509Certificate should be coming from javax.security.cert

Categories

Resources