getting an exception when trying to initialize ApnsServiceBuilder - java

I need a .p12 file in order to authenticate with Apple's notification servers, and I have found some problems. As I understand, I need to generate the .csr and my private key identifying my machine. So I need to execute a command like this in my local machine:
*$:~/Escritorio/curro/certificados$ openssl req -out CSR.csr -new -newkey rsa:2048 -nodes -keyout privateKey.key
Generating a 2048 bit RSA private key
writing new private key to 'privateKey.key'
Now, with my CSR.csr file, I need to login in to:
https://developer.apple.com/account/ios/certificate/certificateCreate.action?formID=62653259
then I provide the .csr file generated before and the system
gives me a .cer file (aps_development.cer) . Now, with this .cer file I have to generate it .p12 equivalent file. In order to do that, I need to make a .pem file starting from that .cer generated file from Apple. This is the command:
#Ubuntu:~/Escritorio/curro/certificados$ openssl pkcs12 -export -inkey privateKey.key -in developer_identity.pem -out iphone_dev.p12
Enter Export Password:
Verifying
Enter Export Password:
After that I have a .p12 file and I need to initialize an ApnsService instance,
#Component
public class NotificationServer implements Runnable, BeanFactoryAware {
#Autowired
// APNS channel
private ApnsService serviceApns;
private String apns_payload;
#PostConstruct
public void init() {
// build apns service path_to_apns_certificate, absolute path .p12 file
String path_to_apns_certificate = config.getProperty("a-path");
//pass used to generate the .p12 file
String password_apns_cert = config.getProperty("a-path");
log.debug("path_to_apns_certificate: " + path_to_apns_certificate);
//keep an eye with this!, this builder is non thread safe!
ApnsServiceBuilder apnsbuilder = new ApnsServiceBuilder();
String sMaxConections = config.getProperty("maxConections");
log.debug("sMaxConections: " + sMaxConections);
int maxConections = Integer.parseInt(sMaxConections);
apnsbuilder.asPool(maxConections );
String connectWithAppleApns = config.getProperty("apns.production");
log.debug("connectWithAppleApns: " + connectWithAppleApns);
apnsbuilder.withAppleDestination(new Boolean(connectWithAppleApns));
//here the exception is launched!
apnsbuilder.withCert(path_to_apns_certificate, password_apns_cert);
serviceApns =apnsbuilder.build();
}
}
Here is the error message:
Caused by: com.notnoop.exceptions.InvalidSSLConfig: java.io.IOException: failed to decrypt safe contents entry: javax.crypto.BadPaddingException: Given final block not properly padded
at com.notnoop.apns.internal.Utilities.newSSLContext(Utilities.java:88)
at com.notnoop.apns.ApnsServiceBuilder.withCert(ApnsServiceBuilder.java:167)
at com.notnoop.apns.ApnsServiceBuilder.withCert(ApnsServiceBuilder.java:134)
at com.*****.agenda.utils.NotificationServer.init(NotificationServer.java:122)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleElement.invoke(InitDestroyAnnotationBeanPostProcessor.java:346)
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleMetadata.invokeInitMethods(InitDestroyAnnotationBeanPostProcessor.java:299)
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:132)
... 164 more
Caused by: java.io.IOException: failed to decrypt safe contents entry: javax.crypto.BadPaddingException: Given final block not properly padded
at sun.security.pkcs12.PKCS12KeyStore.engineLoad(PKCS12KeyStore.java:1304)
at java.security.KeyStore.load(KeyStore.java:1214)
at com.notnoop.apns.internal.Utilities.newSSLContext(Utilities.java:85)
... 174 more
Caused by: javax.crypto.BadPaddingException: Given final block not properly padded
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:811)
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:676)
at com.sun.crypto.provider.PKCS12PBECipherCore.implDoFinal(PKCS12PBECipherCore.java:355)
at com.sun.crypto.provider.PKCS12PBECipherCore$PBEWithSHA1AndRC2_40.engineDoFinal(PKCS12PBECipherCore.java:462)
at javax.crypto.Cipher.doFinal(Cipher.java:2087)
at sun.security.pkcs12.PKCS12KeyStore.engineLoad(PKCS12KeyStore.java:1295)
... 176 more
Can anyone give my any perspective on this?

I response myself. That error involves an error with the pass or the user, in my case the pass that was saved with quotes!! days without seen that mistake.

Related

Problems with grpc connection using ssl

I am currently new in grpc.
I wanted to provide ssl for my grpc server
the javav code for starting looks like this:
InputStream publicKey = ServerStarter.class.getResourceAsStream("/my-public-key-cert.pem");
InputStream privateKey = ServerStarter.class.getResourceAsStream("/my-private-key.pem");
SslContext sslContext = GrpcSslContexts.forServer(publicKey, privateKey).build();
Server server = NettyServerBuilder.forPort(5555)
.sslContext(sslContext)
.addService(new RedirectService())
.intercept(new AuthorizationInterceptor())
.build();
server.start();
SSL certificates were generated with openssl. And here how openssl command looks like:
openssl req -x509 -newkey rsa:4096 -keyout ./grpc-server/src/main/resources/my-private-key.pem -out ./grpc-server/src/main/resources/my-public-key-cert.pem -days 365 -nodes -subj "/CN=192.168.88.132" -addext "subjectAltName = DNS.1:192.168.88.132, DNS.2:localhost"
Server runs fine.
But I can't connect to server.
My clients code looks like this:
InputStream certificate = GalamatClient.class.getResourceAsStream("/my-public-key-cert.pem");
SslContext context = GrpcSslContexts.forClient().trustManager(certificate).build();
ManagedChannel channel = NettyChannelBuilder.forTarget("192.168.88.132:5555")
.sslContext(context)
.build();
GreetingServiceGrpc.GreetingServiceBlockingStub stub = GreetingServiceGrpc.newBlockingStub(channel)
GreetingService.GreetingRequest request = GreetingService.GreetingRequest.newBuilder().setMessage("Hi").build();
GreetingService.GreetingResponse response = stub.greet(request);
channel.shutdownNow();
And when I try to run client next Error occurs:
Exception in thread "main" io.grpc.StatusRuntimeException: UNAVAILABLE: io exception
Channel Pipeline: [SslHandler#0, ProtocolNegotiators$ClientTlsHandler#0, WriteBufferingAndExceptionHandler#0, DefaultChannelPipeline$TailContext#0]
at io.grpc.stub.ClientCalls.toStatusRuntimeException(ClientCalls.java:262)
at io.grpc.stub.ClientCalls.getUnchecked(ClientCalls.java:243)
at io.grpc.stub.ClientCalls.blockingUnaryCall(ClientCalls.java:156)
at com.example.GreetingServiceGrpc$GreetingServiceBlockingStub.recognize(SpeechRecognitionGrpc.java:246)
at com.example.main(Client.java:59)
Caused by: javax.net.ssl.SSLHandshakeException: General OpenSslEngine problem
at io.grpc.netty.shaded.io.netty.handler.ssl.ReferenceCountedOpenSslEngine.handshakeException(ReferenceCountedOpenSslEngine.java:1772)
at io.grpc.netty.shaded.io.netty.handler.ssl.ReferenceCountedOpenSslEngine.wrap(ReferenceCountedOpenSslEngine.java:777)
at javax.net.ssl.SSLEngine.wrap(SSLEngine.java:509)
at io.grpc.netty.shaded.io.netty.handler.ssl.SslHandler.wrap(SslHandler.java:1079)
at io.grpc.netty.shaded.io.netty.handler.ssl.SslHandler.wrapNonAppData(SslHandler.java:970)
at io.grpc.netty.shaded.io.netty.handler.ssl.SslHandler.unwrap(SslHandler.java:1443)
at io.grpc.netty.shaded.io.netty.handler.ssl.SslHandler.decodeJdkCompatible(SslHandler.java:1275)
at io.grpc.netty.shaded.io.netty.handler.ssl.SslHandler.decode(SslHandler.java:1322)
at io.grpc.netty.shaded.io.netty.handler.codec.ByteToMessageDecoder.decodeRemovalReentryProtection(ByteToMessageDecoder.java:501)
at io.grpc.netty.shaded.io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:440)
at io.grpc.netty.shaded.io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:276)
at io.grpc.netty.shaded.io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379)
at io.grpc.netty.shaded.io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365)
at io.grpc.netty.shaded.io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357)
at io.grpc.netty.shaded.io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1410)
at io.grpc.netty.shaded.io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379)
at io.grpc.netty.shaded.io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365)
at io.grpc.netty.shaded.io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:919)
at io.grpc.netty.shaded.io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:166)
at io.grpc.netty.shaded.io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:714)
at io.grpc.netty.shaded.io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:650)
at io.grpc.netty.shaded.io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:576)
at io.grpc.netty.shaded.io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:493)
at io.grpc.netty.shaded.io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:989)
at io.grpc.netty.shaded.io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
at io.grpc.netty.shaded.io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.security.cert.CertificateException: No subject alternative names matching IP address 192.168.88.132 found
at sun.security.util.HostnameChecker.matchIP(HostnameChecker.java:168)
at sun.security.util.HostnameChecker.match(HostnameChecker.java:94)
at sun.security.ssl.X509TrustManagerImpl.checkIdentity(X509TrustManagerImpl.java:459)
at sun.security.ssl.X509TrustManagerImpl.checkIdentity(X509TrustManagerImpl.java:440)
at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:261)
at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:144)
at io.grpc.netty.shaded.io.netty.handler.ssl.OpenSslTlsv13X509ExtendedTrustManager.checkServerTrusted(OpenSslTlsv13X509ExtendedTrustManager.java:223)
at io.grpc.netty.shaded.io.netty.handler.ssl.ReferenceCountedOpenSslClientContext$ExtendedTrustManagerVerifyCallback.verify(ReferenceCountedOpenSslClientContext.java:261)
at io.grpc.netty.shaded.io.netty.handler.ssl.ReferenceCountedOpenSslContext$AbstractCertificateVerifier.verify(ReferenceCountedOpenSslContext.java:698)
at io.grpc.netty.shaded.io.netty.internal.tcnative.SSL.readFromSSL(Native Method)
at io.grpc.netty.shaded.io.netty.handler.ssl.ReferenceCountedOpenSslEngine.readPlaintextData(ReferenceCountedOpenSslEngine.java:596)
at io.grpc.netty.shaded.io.netty.handler.ssl.ReferenceCountedOpenSslEngine.unwrap(ReferenceCountedOpenSslEngine.java:1203)
at io.grpc.netty.shaded.io.netty.handler.ssl.ReferenceCountedOpenSslEngine.unwrap(ReferenceCountedOpenSslEngine.java:1325)
at io.grpc.netty.shaded.io.netty.handler.ssl.SslHandler$SslEngineType$1.unwrap(SslHandler.java:201)
at io.grpc.netty.shaded.io.netty.handler.ssl.SslHandler.unwrap(SslHandler.java:1380)
... 21 more
Suppressed: javax.net.ssl.SSLHandshakeException: error:1000007d:SSL routines:OPENSSL_internal:CERTIFICATE_VERIFY_FAILED
at io.grpc.netty.shaded.io.netty.handler.ssl.ReferenceCountedOpenSslEngine.sslReadErrorResult(ReferenceCountedOpenSslEngine.java:1288)
at io.grpc.netty.shaded.io.netty.handler.ssl.ReferenceCountedOpenSslEngine.unwrap(ReferenceCountedOpenSslEngine.java:1249)
... 24 more
Error says that I don't provide needed Ip in subject alternative names:
No subject alternative names matching IP address 192.168.88.132 found
but I provided it in command of creation certificate.
I will apreciate if you could help with that.
Use overrideAuthority(String authority) to match what the certificate has in its SAN. Use an OpenSsl command to display what you have in your server cert.

Java 8 has broken my application that uses PKCS12

In 2007 I wrote a tiny java application that would digitally sign several different PDF documents (with image of my signature). I has been working great until I upgraded to Java 8.
I am now getting errors:
IOException: Unable to read private key from keystore
e: java.io.IOException: unsupported PKCS12 secret value type 48
I seems now that Java 8 PKCS12 cannot store secret key entries. This is a critical application for me. I use it hundreds of times a day.
How can I work around this issue?
Here is an abridged version of the critical code:
String appPath = SignPDF.class.getProtectionDomain().getCodeSource().getLocation().getPath();
String keytype = "pkcs12";
String keyfile = appPath + "DanVokt.pfx";
String keyimage = appPath + "DanVokt.png";
String keypass = "xxxxxxxxx";
KeyStore ks = KeyStore.getInstance(keytype);
ks.load(new FileInputStream(keyfile), keypass.toCharArray());
String alias = (String)ks.aliases().nextElement();
PrivateKey key = (PrivateKey)ks.getKey(alias, keypass.toCharArray());
Certificate[] chain = ks.getCertificateChain(alias);
PdfReader reader = new PdfReader(ifile);
FileOutputStream fout = new FileOutputStream(ofile);
PdfStamper stp = PdfStamper.createSignature(reader, fout, '\0');
PdfSignatureAppearance sap = stp.getSignatureAppearance();
sap.setCrypto(key, chain, null, PdfSignatureAppearance.SELF_SIGNED);
// allow only printing
stp.setEncryption(null, keypass.getBytes(), PdfWriter.ALLOW_PRINTING,
PdfWriter.STANDARD_ENCRYPTION_128);
stp.close();
Here is a stack tace:
$ signpdf "Timelog*" 1
Processing File: "Timelog - Current Week.pdf" 1
IOException: Unable to read private key from keystore
java.io.IOException: unsupported PKCS12 secret value type 48
at sun.security.pkcs12.PKCS12KeyStore.loadSafeContents(PKCS12KeyStore.java:2197)
at sun.security.pkcs12.PKCS12KeyStore.engineLoad(PKCS12KeyStore.java:2025)
at java.security.KeyStore.load(KeyStore.java:1445)
at SignPDF.main(SignPDF.java:61)
Here is the version and build:
$ java -version
java version "1.8.0_131"
Java(TM) SE Runtime Environment (build 1.8.0_131-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.131-b11, mixed mode)
Attempt to use keytool to view PKCS12 (.pfx) file:
$ keytool -list -keystore DanVokt.pfx -storepass XXXXXXXX -storetype PKCS12 -v
keytool error: java.io.IOException: unsupported PKCS12 secret value type 48
java.io.IOException: unsupported PKCS12 secret value type 48
at sun.security.pkcs12.PKCS12KeyStore.loadSafeContents(PKCS12KeyStore.java:2197)
at sun.security.pkcs12.PKCS12KeyStore.engineLoad(PKCS12KeyStore.java:2025)
at java.security.KeyStore.load(KeyStore.java:1445)
at sun.security.tools.keytool.Main.doCommands(Main.java:795)
at sun.security.tools.keytool.Main.run(Main.java:343)
at sun.security.tools.keytool.Main.main(Main.java:336)
I did a bit of digging. The change appears to have happened as part of some Keystore API enhancements. (They were committed in January 2013)
The specific test is this:
} else if (bagId.equals((Object)SecretBag_OID)) {
DerInputStream ss = new DerInputStream(bagValue.toByteArray());
DerValue[] secretValues = ss.getSequence(2);
ObjectIdentifier secretId = secretValues[0].getOID();
if (!secretValues[1].isContextSpecific((byte)0)) {
throw new IOException(
"unsupported PKCS12 secret value type "
+ secretValues[1].tag);
}
where !(isContextSpecific() is checking the "tag" of the DERvalue to make sure that it doesn't have the CONTEXT bit set. This test is failing.
It would seem that the work-around would be to store these secret keys as DER values with a tag type that doesn't have bit 0x80 set.
See also:
PKCS12KeyStore.java - https://github.com/frohoff/jdk8u-jdk/blob/master/src/share/classes/sun/security/pkcs12/PKCS12KeyStore.java
DERValue.java - https://github.com/frohoff/jdk8u-jdk/blob/master/src/share/classes/sun/security/util/DerValue.java
[RESOLVED]
I created a java keystore (JKS) file:
keytool -genkey -keyalg RSA -keysize 2048 -keystore danv_keystore.jks -alias danv
Of course this created a new private key and new certificate but that is currently not an issue since it is self-signed. I am a bit confused on how to use my own private key and certificate. Any examples?
I then simply changed the keytype and keyfile:
// String keytype = "pkcs12";
String keytype = "JKS";
// String keyfile = appPath + "DanVokt.pfx";
String keyfile = appPath + "danv_keystore.jks";
And voila! It is now working again.
I compiled it under J8 and J7 and it works in both environments.
Thanks!

unable to digitally sign pdf using itext and java

i am trying to put a basic digital signature on a pdf file. i am trying to use the code provided on the itext website.The code is as follows-
public class DigiSign {
public static void main(String a[])
{
try {
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(new FileInputStream("C:\\WSR\\keystore.ks"), "password".toCharArray());
String alias = (String) ks.aliases().nextElement();
PrivateKey key = (PrivateKey) ks.getKey(alias, "password".toCharArray());
java.security.cert.Certificate[] chain = ks.getCertificateChain(alias);
PdfReader reader = new PdfReader("C:\\WSR\\a.pdf");
FileOutputStream fout = new FileOutputStream("C:\\WSR\\signed.pdf");
PdfStamper stp = PdfStamper.createSignature(reader, fout, '\0');
PdfSignatureAppearance sap = stp.getSignatureAppearance();
sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED);
sap.setReason("arpit");
sap.setLocation("arpit");
// comment next line to have an invisible signature
sap.setVisibleSignature(new Rectangle(10, 10, 20, 20), 1, null);
stp.close();
} catch (Exception ex) {
Logger.getLogger(DigiSign.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
i created the key using
keytool -genkey -keyalg RSA -alias myname -keypass password -keystore keystore.ks -dname "cn=Paulo Soares, c=PT"
and set abc123 as my password.
Now when i run this code i get this exception
Exception in thread "main" java.lang.NoClassDefFoundError: org/bouncycastle/asn1/DEREncodable
at com.lowagie.text.pdf.PdfSignatureAppearance.getAppearance(Unknown Source)
at com.lowagie.text.pdf.PdfSignatureAppearance.preClose(Unknown Source)
at com.lowagie.text.pdf.PdfSignatureAppearance.preClose(Unknown Source)
at com.lowagie.text.pdf.PdfStamper.close(Unknown Source)
at DigiSign.main(DigiSign.java:42)
Caused by: java.lang.ClassNotFoundException: org.bouncycastle.asn1.DEREncodable
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
What am i doing wrong?
(Just to formulate the cause as an answer which has been presented as a comment before:)
For security low level operations iText is based on the BouncyCastle libraries. This especially concerns creation and verification of integrated PDF signatures but also handling of encrypted documents. In these use cases, therefore, the appropriate BouncyCastle provider libs are required on the class path of the application.
The primary exception information
java.lang.NoClassDefFoundError: org/bouncycastle/asn1/DEREncodable
indicates that this requirement is not fullfilled, either BouncyCastle is not present at all or at least not present in the required version. This meanwhile has been confirmed by #user1946152 for his configuration.
P.S.: Obviously in the case at hand the OP still uses a pre-5.x version of iText. While there are certain conditions enforcing this (e.g. a management not being willing to decide when to buy a license sigh), you should definitively update to a current version of iText. There meanwhile have been many big changes, especially in the fields of electronic signatures, content parsing, and creation of PDF/A documents.

Java APNS (Apple Push Notification Service) error

I am trying to use Java APNS - an open source project - to send push notifications to iPhones.
I am getting an error, though.
I have used a .pem file as certificate. Should this have been a .p12 file? I am not sure what the difference is, but I read somewhere online that there is a difference between these file formats.
Here is the code:
ApnsService service =
APNS.newService()
.withCert("gpk.pem", "XXXX")
.withSandboxDestination()
.build();
String payload = APNS.newPayload().alertBody("Can't be simpler than this!").build();
String token = "theTokenIsRemoveHere";
service.push(token, payload);
And here is the error:
Exception in thread "main" com.notnoop.exceptions.InvalidSSLConfig: java.io.IOException: toDerInputStream rejects tag type 45
at com.notnoop.apns.internal.Utilities.newSSLContext(Utilities.java:102)
at com.notnoop.apns.ApnsServiceBuilder.withCert(ApnsServiceBuilder.java:161)
at com.notnoop.apns.ApnsServiceBuilder.withCert(ApnsServiceBuilder.java:124)
at com.geomobsters.cli.ApnsClient.main(ApnsClient.java:12)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
Caused by: java.io.IOException: toDerInputStream rejects tag type 45
at sun.security.util.DerValue.toDerInputStream(DerValue.java:806)
at com.sun.net.ssl.internal.pkcs12.PKCS12KeyStore.engineLoad(PKCS12KeyStore.java:1201)
at java.security.KeyStore.load(KeyStore.java:1185)
at com.notnoop.apns.internal.Utilities.newSSLContext(Utilities.java:87)
... 8 more
Java APNS is expecting the cert as .p12 file.
You have to check both privatekey and certificate in your keychain.
then right click-> "export 2 files"
and export them
you have to give it a password, this password you have to type here
.withCert("gpk.pem", "XXXX")
as your XXXX
good luck
EDIT:
.P12 – PKCS#12, contains certificates an private keys saved with a password
.PEM – is Base64-encoded certificate, lockedby „-----BEGIN CERTIFICATE-----“ and „-----END CERTIFICATE-----“

Exception When Reading OCSP Signing Certs in Java

I'm currently working on getting a Java application (JRE 1.5+) to talk to a Windows 2008 OCSP Responder, and I'm getting a strange error on trying to read the Responder's signing cert.
I get the following exception on trying to perform an OCSP validation.
Caused by: java.security.cert.CertificateParsingException: java.io.IOException: short read on DerValue buffer
at sun.security.x509.X509CertInfo.<init>(Unknown Source)
at sun.security.x509.X509CertImpl.parse(Unknown Source)
at sun.security.x509.X509CertImpl.<init>(Unknown Source)
at sun.security.provider.certpath.OCSPResponse.<init>(Unknown Source)
at sun.security.provider.certpath.OCSPChecker.check(Unknown Source)
... 6 more
Caused by: java.io.IOException: short read on DerValue buffer
at sun.security.util.DerValue.getOctetString(Unknown Source)
at sun.security.x509.Extension.<init>(Unknown Source)
at sun.security.x509.CertificateExtensions.init(Unknown Source)
at sun.security.x509.CertificateExtensions.<init>(Unknown Source)
at sun.security.x509.X509CertInfo.parse(Unknown Source)
... 11 more
This suggested there was a problem reading the signing cert, so I tried importing that separately using a method similar to the below:
public static List<Certificate> readCerts(String certFile,
CertificateFactory cf, boolean withCRL) throws Exception {
FileInputStream fis = new FileInputStream(certFile);
BufferedInputStream bis = new BufferedInputStream(fis);
List<Certificate> certs = new LinkedList<Certificate>();
while (bis.available() > 0) {
Certificate cert = cf
.generateCertificate(bis);
X509Certificate cx509 = (X509Certificate) cert;
certs.add(cert);
}
return certs;
}
which gave me the same error. This only seems to happen with certificates generated from the OCSP Signing template, user certificates can be read fine.
Has anyone else encountered similar problems with X509 support in Java?
Regards,
Tom
UPDATE: The cert I'm having trouble with is as below:
-----BEGIN CERTIFICATE-----
MIIDzDCCArSgAwIBAgIKYQWrDAAAAAAABjANBgkqhkiG9w0BAQUFADBFMRMwEQYK
CZImiZPyLGQBGRYDaW50MRUwEwYKCZImiZPyLGQBGRYFbG9ucWExFzAVBgNVBAMT
DmxvbnFhLVRFLUNBLUNBMB4XDTA5MDkyMTE2NDIxNloXDTA5MTAwNTE2NDIxNlow
GjEYMBYGA1UEAxMPdGUtY2EubG9ucWEuaW50MIIBIjANBgkqhkiG9w0BAQEFAAOC
AQ8AMIIBCgKCAQEA6rYO7X/PztBE2Do9u95ws3Ob86cySJ1iLrHLSF+VjvTQkZ3J
e0uKxoK4doSikqCZH9zXZ6qFFVMZlzq/FnIP9TLhv3uFom0y+Z0HmPAW7RtrZ8R6
1EAmcQDGpyRhzCWJqrEzgbW1v1QtF854kium97GwUWnVijGv3jQqT3hbmD7++9lh
9ILaLXMAKdTFpL1ao2eHWYf2mChRpuAox2juO1g4xjot9GXsEMhTwAg9F/pZnbKE
hhpeo1c0kgP3uus7ULlwdRnZ4O+tp79GeVKsdJbphmnC6Fc/PdT0KuHSk9Q0v192
Ger5nTQaZk/dmsyGBd8g4Q+0g0Ri+wgpUUsykQIDAQABo4HoMIHlMDYGCSsGAQQB
gjcVBwQpMCcGHysGAQQBgjcVCIHPgWyXxQ2ChYcyg8LhMoWky3ppASACAWUCAQAw
EwYDVR0lBAwwCgYIKwYBBQUHAwkwDgYDVR0PAQH/BAQDAgeAMBsGCSsGAQQBgjcV
CgQOMAwwCgYIKwYBBQUHAwkwDQYJKwYBBQUHMAEFBAAwHQYDVR0OBBYEFNblspp7
Hu07mraeMSyuBUTUnbl3MB8GA1UdIwQYMBaAFK/r521FB+GNls/fe8hrNE8UpQhv
MBoGA1UdEQQTMBGCD3RlLWNhLmxvbnFhLmludDANBgkqhkiG9w0BAQUFAAOCAQEA
FASEVcUJQlrmCD/ysycOxAIAoc2BVLhteOMoZ7V65a5/+Q5JM7Od+gKqoxLVrjb2
BDLlDFp5U8CirQ4lyWV5i1gQpLFTDcjgonp9Ky50KA0Ginn5CmTELB2THwFSQwfm
OFenSaV1mAcEzdyp/hi2xSuMqhveSanQFD0r6y45oZsd9ubdFEWI6nBRrj4hhfw0
Wo2GKUgslXqAqEezdin5JNgsPdj3qsi4+U4llyrd3gG20eoWzGHF4h7wfFiQV+fs
yEPY06Rg9G9m3GlIv+7Gp3sixb+cvZe+e0gO32mVRydTXMaAZu7ZiFk3M6AqxfDw
dO//eCu2dZCLTw6xTbUc9A==
-----END CERTIFICATE-----
I assume you get your factory like this,
cf = CertificateFactory.getInstance("X509");
The default X509 factory has many limitations. It looks like your cert contains an extension the factory doesn't know how to parse. If you post the cert, I can help you to identify the offending extension.
EDIT: The offending extension is
1.3.6.1.5.5.7.48.1.5 - id-pkix-ocsp-nocheck
The only option is to remove this from the cert with Java built-in JCE. You can also try another JCE like BouncyCastle.

Categories

Resources