• RELEVANCY SCORE 3.19

    DB:3.19:Cast From Crlentry To X509certificate Problem pp





    hey,

    i use the following code to cast from CRLEntry to X509Certificate.
    X509CRL crl = ldap.getCRL();
    System.out.println("ldap crl: "+crl.getIssuerDN());
    Iterator revokedCerts = crl.getRevokedCertificates().iterator();
    while(revokedCerts.hasNext() ) {
    X509CRLEntry ce = (X509CRLEntry)revokedCerts.next();
    System.out.println("Certificate serial (CRLEntry): "+ ce.getSerialNumber());
    X509Certificate cert = (X509Certificate) cf.generateCertificate( new ByteArrayInputStream(ce.getEncoded()));
    System.out.println("Certificate serial (X509Certificate): "+ cert.getSerialNumber());
    }Everything works fine till it reaches the line X509Certificate cert = (X509Certificate) cf.generateCertificate( new ByteArrayInputStream(ce.getEncoded())); it throws the following Exception:
    Exception in thread "main" java.security.cert.CertificateException: java.lang.IllegalArgumentException: sequence wrong size for a certificate
    at org.bouncycastle.jce.provider.JDKX509CertificateFactory.engineGenerateCertificate(JDKX509CertificateFactory.java:272)
    at java.security.cert.CertificateFactory.generateCertificate(CertificateFactory.java:271)
    at pkiUniTrust.ProjetTest.main(ProjetTest.java:72)
    Java Result: 1does there exist another possibility to convert the CRLEntry to an X509Certificate?

    many thanks

    toto

    DB:3.19:Cast From Crlentry To X509certificate Problem pp

    hey ghstark,

    as i read your post i was wondering why i did this "stupid" mistake :). it's absolutely clear that the CRLEntry does not contain any certificate.
    well that happens when one works till 4 am :).

    thanks

    toto

  • RELEVANCY SCORE 3.16

    DB:3.16:Problem Configing Wls 9 Ws Security Samples W/ New Keys zm





    I am trying to modify the WebLogic "samples" webservices/security_jws example in Weblogic 9 to use a user-defined keystore and keytool generated keys and certs. So far I have modified to code to pull encoded certs from a keystore instead of the provided sample *.der files for cert and private keys. I use a different constructor as follows: ClientBSTCredentialProvider(X509Certificate, PrivateKey, X509Certificate); I build the X509Certificate by pulling certs from a JKS keystore:

    java.security.cert.CertificateFactory cf = java.security.cert.CertificateFactory.getInstance("X.509");
    Certificate c1 = keystore.getCertificate(certAlias);
    java.io.ByteArrayInputStream bais1 = null;
    try {
    bais1 = new java.io.ByteArrayInputStream(c1.getEncoded());
    serverCertificate = (X509Certificate)cf.generateCertificate(bais1);
    } finally {bais1.close();}

    I have configured Web Service Security in the domain using "default_wss". I have configured Confidentiality and Integrity settings pointing to file system-based keystores of integrity.jks and confidentiality.jks. Passphrases are checked for encrypt. I assume I need to use my alias instead of the instruction's "Bob" and passphrase of "true". I have added my client's cert to the JDK's cacerts as a trusted cert. I have imported the server identity cert to the client.jks

    The server and client build and deploy. When I run the client I get the following error. I have also tried creating an X509 TokenHandler and adding X509 to my security realm's IdentityAsserter using Default Mapper.

    I am not using a Certificate Authority signed cert.

    Should I be using *.der files and BEA CA signed certs with BEA supplied key generator?

    [java] /detail]; nested exception is:
    [java] javax.xml.rpc.soap.SOAPFaultException: weblogic.xml.crypto.wss.WSSecurityException: weblogic.xml.crypto.encrypt.api.XMLEncryptionException: com.rsa.jsafe.JSAFE_PaddingException: The input requires padding, but NoPad was instantiated.weblogic.xml.crypto.encrypt.api.XMLEncryptionException: com.rsa.jsafe.JSAFE_PaddingException: The input requires padding, but NoPad was instantiated.
    [java] at examples.webservices.security_jws.client.SecureHelloWorldPortType_Stub.sayHello(SecureHelloWorldPortType_Stub.java:37)
    [java] at examples.webservices.security_jws.SecureHelloWorldClient.main(SecureHelloWorldClient.java:154)
    [java] Caused by: javax.xml.rpc.soap.SOAPFaultException: weblogic.xml.crypto.wss.WSSecurityException: weblogic.xml.crypto.encrypt.api.XMLEncryptionException: com.rsa.jsafe.JSAFE_PaddingException: The input requires padding, but NoPad was instantiated.weblogic.xml.crypto.encrypt.api.XMLEncryptionException: com.rsa.jsafe.JSAFE_PaddingException: The input requires padding, but NoPad was instanti
    ated.

    DB:3.16:Problem Configing Wls 9 Ws Security Samples W/ New Keys zm

    I am trying to modify the WebLogic "samples" webservices/security_jws example in Weblogic 9 to use a user-defined keystore and keytool generated keys and certs. So far I have modified to code to pull encoded certs from a keystore instead of the provided sample *.der files for cert and private keys. I use a different constructor as follows: ClientBSTCredentialProvider(X509Certificate, PrivateKey, X509Certificate); I build the X509Certificate by pulling certs from a JKS keystore:

    java.security.cert.CertificateFactory cf = java.security.cert.CertificateFactory.getInstance("X.509");
    Certificate c1 = keystore.getCertificate(certAlias);
    java.io.ByteArrayInputStream bais1 = null;
    try {
    bais1 = new java.io.ByteArrayInputStream(c1.getEncoded());
    serverCertificate = (X509Certificate)cf.generateCertificate(bais1);
    } finally {bais1.close();}

    I have configured Web Service Security in the domain using "default_wss". I have configured Confidentiality and Integrity settings pointing to file system-based keystores of integrity.jks and confidentiality.jks. Passphrases are checked for encrypt. I assume I need to use my alias instead of the instruction's "Bob" and passphrase of "true". I have added my client's cert to the JDK's cacerts as a trusted cert. I have imported the server identity cert to the client.jks

    The server and client build and deploy. When I run the client I get the following error. I have also tried creating an X509 TokenHandler and adding X509 to my security realm's IdentityAsserter using Default Mapper.

    I am not using a Certificate Authority signed cert.

    Should I be using *.der files and BEA CA signed certs with BEA supplied key generator?

    [java] /detail]; nested exception is:
    [java] javax.xml.rpc.soap.SOAPFaultException: weblogic.xml.crypto.wss.WSSecurityException: weblogic.xml.crypto.encrypt.api.XMLEncryptionException: com.rsa.jsafe.JSAFE_PaddingException: The input requires padding, but NoPad was instantiated.weblogic.xml.crypto.encrypt.api.XMLEncryptionException: com.rsa.jsafe.JSAFE_PaddingException: The input requires padding, but NoPad was instantiated.
    [java] at examples.webservices.security_jws.client.SecureHelloWorldPortType_Stub.sayHello(SecureHelloWorldPortType_Stub.java:37)
    [java] at examples.webservices.security_jws.SecureHelloWorldClient.main(SecureHelloWorldClient.java:154)
    [java] Caused by: javax.xml.rpc.soap.SOAPFaultException: weblogic.xml.crypto.wss.WSSecurityException: weblogic.xml.crypto.encrypt.api.XMLEncryptionException: com.rsa.jsafe.JSAFE_PaddingException: The input requires padding, but NoPad was instantiated.weblogic.xml.crypto.encrypt.api.XMLEncryptionException: com.rsa.jsafe.JSAFE_PaddingException: The input requires padding, but NoPad was instanti
    ated.

  • RELEVANCY SCORE 3.15

    DB:3.15:Length Tag=109, Too Big df





    Hi,

    I created a certificate using java keytool (JDK 1.4.2 )

    No matter which proivder i use (IBMJCE or BouncyCastle to name a couple)

    I keep getting this error.

    public X509Certificate getCertificate() {
    try {

    InputStream inStream = new FileInputStream(SERVER_KEYSTORE);
    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    X509Certificate cert = (X509Certificate) cf.generateCertificate(inStream);
    inStream.close();
    return cert;
    }
    catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    throw new RuntimeException(e);
    }
    }

    java.security.cert.CertificateException: Unable to initialize, java.io.IOException: DerInputStream.getLength(): lengthTag=109, too big.
    at com.ibm.security.x509.X509CertImpl.init(Unknown Source)
    at com.ibm.security.x509.X509CertImpl.init(Unknown Source)
    at com.ibm.crypto.provider.X509Factory.engineGenerateCertificate(Unknown Source)
    at java.security.cert.CertificateFactory.generateCertificate(Unknown Source)
    at samples.EncyrptionSamples.getCertificate(EncyrptionSamples.java:113)
    at samples.EncyrptionSamples.encrypt(EncyrptionSamples.java:91)
    at samples.EncyrptionSamples.main(EncyrptionSamples.java:62)

    Appreciate if somebody could point me to what is wrong out here.

    Thanks,
    manglu

    DB:3.15:Length Tag=109, Too Big df

    A keystore file is not just a collection of X509 certificates. It has a more complicated structure. You need to use the KeyStore API to access information in a keystore.

  • RELEVANCY SCORE 3.14

    DB:3.14:Need Help With Contacting Https Url 9x


    Hi,
    I am new bie to Java Security. I do not know where to start off with. Here is the requirement.

    I need to contact an HTTPS URL and this URL gives me output which is encypted data.
    I have to save this ecnrypted data into a file and I have the KEY to decrypt the data.

    I have tried several ways (all listed below) to get it working. But I am not successful. I get
    "javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: No trusted certificate found"

    Can you guys give me some insight on how to proceed?

    Thanks
    Mathew

    import java.util.*;
    import java.text.*;
    import java.net.*;
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.security.Permission;
    import javax.net.ssl.HttpsURLConnection;
    import java.security.*;
    import java.security.cert.*;
    import javax.net.ssl.*;
    import java.io.*;

    public class temp
    {
    protected BufferedReader messageResponseReader;
    private static final String CERTIFICATE_TYPE = "SunX509";
    private static final String KEYSTORE_TYPE = "JKS";
    private static final String SSL_PROTOCOL = "TLS";
    private static final String CERTIFICATE_FACTORY_TYPE = "X.509";

    public static void main(String args[])
    {

    try
    {

    try{
    temp tmp = new temp();
    String url = "https://test.mysite.com/one/perform.jsp?mode=getcheck=true";
    tmp.sendRequest(url);
    }catch(Exception e)
    {
    e.printStackTrace();
    }
    }
    catch(Exception e){
    e.printStackTrace();
    }

    }

    public String sendRequest(String urlString) throws Exception
    {
    StringBuffer response = null;
    BufferedReader messageReader = null;

    try
    {
    String username = "user";
    String password = "pwd";
    String encoding = new sun.misc.BASE64Encoder().encode("username:password".getBytes());

    //java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
    //System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");

    // Needed for validation of the server certificate
    //System.setProperty("javax.net.ssl.trustStore","C:\\cert\\key.txt");
    // Needed for providing a clint certificate for client authentication
    //System.setProperty("javax.net.ssl.keyStore","C:\\cert\\key.txt");
    //System.setProperty("javax.net.ssl.keyStorePassword","te5t1ng");
    //System.setProperty("ssl.SocketFactory.provider", "com.sun.net.ssl.internal.ssl.Provider");

    /*

    KeyStore ks;
    ks = KeyStore.getInstance("JKS");
    CertificateFactory cf = CertificateFactory.getInstance(CERTIFICATE_FACTORY_TYPE);
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(CERTIFICATE_TYPE);
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(CERTIFICATE_TYPE);

    FileInputStream fis = new FileInputStream("C:\\cert\\key.txt");
    BufferedInputStream bis = new BufferedInputStream(fis);

    Collection c = cf.generateCertificates(fis);
    Iterator i = c.iterator();
    while (i.hasNext()) {
    java.security.cert.Certificate cert = (java.security.cert.Certificate)i.next();
    System.out.println(cert);
    }

    ks.load(null, null);
    X509Certificate the_cert = (X509Certificate)cf.generateCertificate(bis);
    ks.setCertificateEntry("server_cert",the_cert);
    tmf.init(ks);

    ks = KeyStore.getInstance(KEYSTORE_TYPE);
    ks.load(null, null);
    the_cert = (X509Certificate)cf.generateCertificate(new FileInputStream("key.txt"));
    ks.setCertificateEntry("client_cert",the_cert);
    kmf.init(ks, null);

    SSLContext ctx = SSLContext.getInstance(SSL_PROTOCOL);
    KeyManager[] km = kmf.getKeyManagers();
    TrustManager[] tm = tmf.getTrustManagers();
    ctx.init (km, tm, null);

    HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());

    */

    urlString = urlString.replaceAll(" ","%20");
    URL url = new URL(urlString);

    //HttpsURLConnection urlCon = (HttpsURLConnection)url.openConnection();
    HttpURLConnection urlCon = (HttpURLConnection)url.openConnection();
    //com.sun.net.ssl.HttpsURLConnection urlCon = (com.sun.net.ssl.HttpsURLConnection)urlCon;

    /*urlCon.setRequestProperty("Host", url.getHost());*/
    urlCon.setDoOutput(true);
    urlCon.setDoInput(true);
    urlCon.setRequestMethod("POST");
    urlCon.setUseCaches (false);
    urlCon.setAllowUserInteraction(true);
    urlCon.setInstanceFollowRedirects(true);
    urlCon.setRequestProperty ("Authorization", "Basic " + encoding);

    //Permission permision = urlCon.getPermission();
    //System.out.println("permission name:"+permision.getName());

    urlCon.connect();

    //messageReader = new BufferedReader(new InputStreamReader(urlCon.getInputStream()));
    //response = new StringBuffer();
    //String line;

    //while((line = messageReader.readLine()) != null){
    // response.append(line);
    // response.append("\n");
    //}
    }
    catch (Exception e) {

    e.printStackTrace();
    throw e;
    }
    return "testing";
    }

    }

    DB:3.14:Need Help With Contacting Https Url 9x

    Hello!

    I am struggling with the same problem too...

    somebody.... :,( anybody???

  • RELEVANCY SCORE 3.05

    DB:3.05:How To Get Thumbprint Of A Cert?? s9


    Hi,
    I use 1.4.2 jdk. I need to have secure communications with Directory servers - meaning work with SSLs. I want to get the value of thumbprint of an X509Certificate retrieved from a directory server. How can I do that? I realized there is no direct method call on X509Certificate class.

    Searching online blessed me with a link related to this:
    http://archives.java.sun.com/cgi-bin/wa?A2=ind0407L=java-securityF=S=P=4456
    I used the following method to convert bytes into Hexadecimal strings:
    ******************
    static String toHexString(byte[] buf, int off, int len)
    {
    StringBuffer str = new StringBuffer();
    for (int i = 0; i len; i++)
    {
    String HEX = "0123456789abcdef";
    str.append(HEX.charAt(buf[i+off] 4 0x0F));
    str.append(HEX.charAt(buf[i+off] 0x0F));
    }
    return str.toString();
    }
    *********************************

    The resultant string is a valid String, but it does not look like a Thumbprint. it looks some thing like "acedbc024h759jkdhuu2885973jh8dgjj5", as oppsed to a typical Thumprint looking like "2f f7 67 uy 92 g4 r4 57 5h j7 h2 8f".

    I would appreciate the help.

    DB:3.05:How To Get Thumbprint Of A Cert?? s9

    I'm having the same issue.And the answer is the same too, oddly enough. Please read the thread before you post.

    Locking it.

  • RELEVANCY SCORE 3.03

    DB:3.03:How To Import Certificate X509certificate Object In To Smart Card Using Vc++. 81



    Hello,

    I need Information (Functions) regarding How to Import Certificate (*.crt) to Smart Card using VC.

    Currently I have certificate with extension .crt and I need to write/import that certificate in to Smart Card using Crypto API functions.

    Please let me know Steps or any Sample Code if you have.

    Currently I am able to read certificate objectX509Certificate with below code but how can i write that object in smart card.

    String^ Certificate = LD:\\02020202.crt;

    // Load the certificate into an X509Certificate object.
    X509Certificate^ cert = gcnew X509Certificate(Certificate);

    Here cert object showing me all information regarding Certificate, but I am not able to Import/write that object in smart card, please do need full.

    Thanks in advance.

    DB:3.03:How To Import Certificate X509certificate Object In To Smart Card Using Vc++. 81

    HiEileen,
    Thanks forresponse, but I am not able to import certificate in Smart card by usingInstallResponsemethod
    :(
    I am using below code.

    System.IO.TextReader tr = new System.IO.StreamReader(D:\\certificate\\ISampleCert.cer);
    string strResp = tr.ReadToEnd();
    tr.Close();
    // Install the certificate
    objEnroll.Initialize(X509CertificateEnrollmentContext.ContextUser);

    objEnroll.InstallResponse(
    InstallResponseRestrictionFlags.AllowUntrustedRoot,
    strResp,
    EncodingType.XCN_CRYPT_STRING_BASE64HEADER,
    null
    );
    but after Install Responce method its throwing an error message. Object Property not found :(
    is any correction are required?

  • RELEVANCY SCORE 3.00

    DB:3.00:Migrating From Java To Weblogic Ssl Implementation, Sslcontext 8k


    Hi,

    In java SSLContext.init(keyManagers, trustManagers, null) we pass keyManagers and trustManagers to init it, these managers can be created for example like this:

    KeyManagerFactory kmfactory = KeyManagerFactory
    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmfactory.init(keystore, password != null ? password.toCharArray()
    : null);
    return kmfactory.getKeyManagers();then I can call sslContext.getSocketFactory() and pass it to HttpsURLConnection - ready and works..

    In weblogic classes in SSLContext I don't have init() method, dont have something like KeyManagerFactory ...

    I can get this factory by calling sslContext.getSocketFactory() but firstly I must create and initialize SSLContext.

    Here's the problem:

    KeyStore keystore = (I use java classes, that is simple)

    weblogic.security.SSL.SSLContext sslcontext = weblogic.security.SSL.SSLContext.getInstance("https");
    weblogic.security.SSL.TrustManager tm = what??? - no any factory that could be initialized by keyStore and would have getTrustManagers() ;

    And then sslcontext.setTrustManager(tmanager); - which one? No init method in some factory, that would start the whole SSL engine..
    In samples there is NulledTrustManager that does nothing so how to create such manager basing on java.security.KeyStore? - because I have to check all the aliases and respec certificate chains and return some result.. In Java classes it hapens automatically and it can be done like this:

    public class AuthSSLX509TrustManager implements X509TrustManager {
    private X509TrustManager defaultTrustManager = null;
    private static Logger log = Logger.getLogger(AuthSSLX509TrustManager.class);
    ;

    /**
    * Constructor for AuthSSLX509TrustManager.
    */
    public AuthSSLX509TrustManager(final X509TrustManager defaultTrustManager) {
    super();
    if (defaultTrustManager == null) {
    throw new IllegalArgumentException("Trust manager may not be null");
    }
    this.defaultTrustManager = defaultTrustManager;
    }

    /**
    * @see javax.net.ssl.X509TrustManager#checkClientTrusted(X509Certificate[],String
    * authType)
    */
    public void checkClientTrusted(X509Certificate[] certificates,
    String authType) throws CertificateException {
    System.out.println(" checkClientTrusted!! ");
    if (certificates != null) {
    for (int c = 0; c certificates.length; c++) {
    X509Certificate cert = certificates[c];
    System.out.println(" Client certificate " + (c + 1) + ":");
    System.out.println(" Subject DN: " + cert.getSubjectDN());
    System.out.println(" Signature Algorithm: " + cert.getSigAlgName());
    System.out.println(" Valid from: " + cert.getNotBefore());
    System.out.println(" Valid until: " + cert.getNotAfter());
    System.out.println(" Issuer: " + cert.getIssuerDN());
    }
    } else {
    System.out.println(" certificates are null!! ");

    }
    defaultTrustManager.checkClientTrusted(certificates, authType);
    }

    /**
    * @see javax.net.ssl.X509TrustManager#checkServerTrusted(X509Certificate[],String
    * authType)
    */
    public void checkServerTrusted(X509Certificate[] certificates,
    String authType) throws CertificateException {
    System.out.println(" checkServerTrusted!! ");
    if (certificates != null) {
    for (int c = 0; c certificates.length; c++) {
    X509Certificate cert = certificates[c];
    System.out.println(" Server certificate " + (c + 1) + ":");
    System.out.println(" Subject DN: " + cert.getSubjectDN());
    System.out.println(" Signature Algorithm: " + cert.getSigAlgName());
    System.out.println(" Valid from: " + cert.getNotBefore());
    System.out.println(" Valid until: " + cert.getNotAfter());
    System.out.println(" Issuer: " + cert.getIssuerDN());
    }
    } else {
    System.out.println(" certificates are null!! ");

    }
    defaultTrustManager.checkServerTrusted(certificates, authType);
    }

    /**
    * @see javax.net.ssl.X509TrustManager#getAcceptedIssuers()
    */
    public X509Certificate[] getAcceptedIssuers() {
    return this.defaultTrustManager.getAcceptedIssuers();
    }
    }What is important is that I want to have my own location of keystore file, like D:\\certs\blabla..

    In samples there is NulledTrustManager that does nothing so how to create such manager basing on java.security.KeyStore? - because I have to check all the aliases and respec certificate chains and return some result.. In Java classes it hapens automatically

    In Weblogic it is not so easy- can u pass me some examples please? I want to create weblogic HttpsURLConnection and pass to it respect data like hostnameverifier or socketfactory, dont want to make all of it using sockets, i did such client with java SSL classes, i need help with weblogic solution.

    --
    Edited by haiaw at 02/28/2007 4:35 AM

    DB:3.00:Migrating From Java To Weblogic Ssl Implementation, Sslcontext 8k

    You're asking questions about WebLogic here. Try a WebLogic forum.

    I don't know anything about WebLogic but I'd be surprised if the standard JSSE code wouldnt' continue to work. I don't know why you need all this vendor-specific stuff.

  • RELEVANCY SCORE 2.93

    DB:2.93:How To Use Custom Truststore? 3a


    Hi, I've written a simple ssl client (basing on jakarta commons httpclient project) that connects to IIS with SSL and it works only i f I add ssl certificate from IIS to the jre cacerts (using keytool import). The cacerts are automatically readed somehow (don't know how)
    I want to make the whole thing more elastic and be able to provide my client with a path to cacerts / truststore / keystore. Am I doing it OK? I Currently it works...

    BUT the loops that print certificates and trustores to screen are empty - for example keystore.getCertificateChain(alias); always returns null....

    But IIS cert is inside
    C:\\Program Files\\Java\\jre1.5.0_09\\lib\\security\\cacertsbbb

    PS. I would like to avoid setting System properties in my code like System.setTruststore etc.
    PS. Should be without sockets. Just extension of what i got.

    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.InetAddress;
    import java.net.InetSocketAddress;
    import java.net.MalformedURLException;
    import java.net.Socket;
    import java.net.SocketAddress;
    import java.net.URL;
    import java.net.UnknownHostException;
    import java.security.GeneralSecurityException;
    import java.security.KeyStore;
    import java.security.KeyStoreException;
    import java.security.NoSuchAlgorithmException;
    import java.security.UnrecoverableKeyException;
    import java.security.cert.Certificate;
    import java.security.cert.CertificateException;
    import java.security.cert.X509Certificate;
    import java.util.Enumeration;

    import javax.net.SocketFactory;
    import javax.net.ssl.HostnameVerifier;
    import javax.net.ssl.HttpsURLConnection;
    import javax.net.ssl.KeyManager;
    import javax.net.ssl.KeyManagerFactory;
    import javax.net.ssl.SSLContext;
    import javax.net.ssl.SSLSession;
    import javax.net.ssl.SSLSocketFactory;
    import javax.net.ssl.TrustManager;
    import javax.net.ssl.TrustManagerFactory;
    import javax.net.ssl.X509TrustManager;

    import org.apache.commons.httpclient.ConnectTimeoutException;
    import org.apache.commons.httpclient.params.HttpConnectionParams;
    import org.apache.log4j.Logger;

    import junit.framework.TestCase;

    public class SSLSocketClient extends TestCase {

    private URL keystoreUrl = null;

    private String mockKeystoreUrl = "C:\\Program Files\\Java\\jre1.5.0_09\\lib\\security\\cacertsbbb";

    private String keystorePassword = "changeit";

    private URL truststoreUrl = null;

    private String mockTruststoreUrl = "C:\\Program Files\\Java\\jre1.5.0_09\\lib\\security\\cacertsbbb";

    private String truststorePassword = null;

    private SSLContext sslcontext = null;

    //

    public void testSSLSocket() {
    try {
    SSLSocketClient client = new SSLSocketClient();

    // client.createSocket("10.63.29.50", 443);

    HttpConnectionParams params = new HttpConnectionParams();
    InetAddress ia = InetAddress.getLocalHost();
    // params.setParameter(arg0, arg1)

    //client.createSocket("10.63.29.50", 443, ia, 444, params);

    client.connect("10.63.29.50", 443, "/ssl2/index.html", params);
    } catch (ConnectTimeoutException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (UnknownHostException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }

    }

    private static Logger log = Logger.getLogger(SSLSocketClient.class);

    /*
    * private static KeyStore createKeyStore(final URL url, final String
    * password) throws KeyStoreException, NoSuchAlgorithmException,
    * CertificateException, IOException { if (url == null) { throw new
    * IllegalArgumentException("Keystore url may not be null"); }
    *
    * KeyStore keystore = KeyStore.getInstance("jks");
    * keystore.load(url.openStream(), password != null ? password
    * .toCharArray() : null); return keystore; }
    */

    private KeyStore mockCreateKeyStore(final String url, final String password)
    throws KeyStoreException, NoSuchAlgorithmException,
    CertificateException, IOException {
    if (url == null) {
    throw new IllegalArgumentException("Keystore url may not be null");
    }
    InputStream keystoreStream = new FileInputStream(url);

    KeyStore keystore = KeyStore.getInstance("jks");
    keystore.load(keystoreStream, password != null ? password.toCharArray()
    : null);
    return keystore;
    }

    private KeyManager[] createKeyManagers(final KeyStore keystore,
    final String password) throws KeyStoreException,
    NoSuchAlgorithmException, UnrecoverableKeyException {
    if (keystore == null) {
    throw new IllegalArgumentException("Keystore may not be null");
    }

    KeyManagerFactory kmfactory = KeyManagerFactory
    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmfactory.init(keystore, password != null ? password.toCharArray()
    : null);
    return kmfactory.getKeyManagers();
    }

    private TrustManager[] createTrustManagers(final KeyStore keystore)
    throws KeyStoreException, NoSuchAlgorithmException {
    if (keystore == null) {
    throw new IllegalArgumentException("Keystore may not be null");
    }

    TrustManagerFactory tmfactory = TrustManagerFactory
    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmfactory.init(keystore);
    TrustManager[] trustmanagers = tmfactory.getTrustManagers();
    for (int i = 0; i trustmanagers.length; i++) {
    if (trustmanagers[i] instanceof X509TrustManager) {
    trustmanagers[i] = new AuthSSLX509TrustManager(
    (X509TrustManager) trustmanagers);
    }
    }
    return trustmanagers;
    }

    private SSLContext createSSLContext() {
    try {
    KeyManager[] keymanagers = null;
    TrustManager[] trustmanagers = null;
    if (this.mockKeystoreUrl != null) {
    KeyStore keystore = mockCreateKeyStore(this.mockKeystoreUrl,
    this.keystorePassword);
    //if (log.isDebugEnabled()) {
    Enumeration aliases = keystore.aliases();
    while (aliases.hasMoreElements()) {
    String alias = (String) aliases.nextElement();
    Certificate[] certs = keystore
    .getCertificateChain(alias);
    if (certs != null) {
    log.info("Certificate chain '" + alias + "':");
    for (int c = 0; c certs.length; c++) {
    if (certs[c] instanceof X509Certificate) {
    X509Certificate cert = (X509Certificate) certs[c];
    log.info(" Certificate " + (c + 1) + ":");
    log.info(" Subject DN: "
    + cert.getSubjectDN());
    log.info(" Signature Algorithm: "
    + cert.getSigAlgName());
    log.info(" Valid from: "
    + cert.getNotBefore());
    log.info(" Valid until: "
    + cert.getNotAfter());
    log
    .info(" Issuer: "
    + cert.getIssuerDN());
    }
    }
    }
    }
    //}
    keymanagers = createKeyManagers(keystore, this.keystorePassword);
    }
    if (this.mockTruststoreUrl != null) {
    KeyStore keystore = mockCreateKeyStore(this.mockKeystoreUrl,
    this.truststorePassword);
    //if (log.isDebugEnabled()) {
    Enumeration aliases = keystore.aliases();
    while (aliases.hasMoreElements()) {
    String alias = (String) aliases.nextElement();
    log.debug("Trusted certificate '" + alias + "':");
    Certificate trustedcert = keystore
    .getCertificate(alias);
    if (trustedcert != null
    trustedcert instanceof X509Certificate) {
    X509Certificate cert = (X509Certificate) trustedcert;
    log.info(" Subject DN: " + cert.getSubjectDN());
    log.info(" Signature Algorithm: "
    + cert.getSigAlgName());
    log.info(" Valid from: " + cert.getNotBefore());
    log.info(" Valid until: " + cert.getNotAfter());
    log.info(" Issuer: " + cert.getIssuerDN());
    }
    }
    //}
    trustmanagers = createTrustManagers(keystore);
    }
    SSLContext sslcontext = SSLContext.getInstance("SSL");
    ///sslcontext.
    sslcontext.init(keymanagers, trustmanagers, null);
    return sslcontext;
    } catch (NoSuchAlgorithmException e) {
    log.error(e.getMessage(), e);
    throw new RuntimeException("Unsupported algorithm exception: "
    + e.getMessage());
    // throw new AuthSSLInitializationError("Unsupported algorithm
    // exception: " + e.getMessage());
    } catch (KeyStoreException e) {
    log.error(e.getMessage(), e);
    throw new RuntimeException("Keystore exception: " + e.getMessage());
    // throw new AuthSSLInitializationError("Keystore exception: " +
    // e.getMessage());
    } catch (GeneralSecurityException e) {
    log.error(e.getMessage(), e);
    throw new RuntimeException("Key management exception: "
    + e.getMessage());
    // throw new AuthSSLInitializationError("Key management exception: "
    // + e.getMessage());
    } catch (IOException e) {
    log.error(e.getMessage(), e);
    throw new RuntimeException(
    "I/O error reading keystore/truststore file: "
    + e.getMessage());
    // throw new AuthSSLInitializationError("I/O error reading
    // keystore/truststore file: " + e.getMessage());
    }
    }

    private SSLContext getSSLContext() {
    if (this.sslcontext == null) {
    this.sslcontext = createSSLContext();
    }
    return this.sslcontext;
    }

    /**
    * Attempts to get a new socket connection to the given host within the
    * given time limit.
    * p
    * To circumvent the limitations of older JREs that do not support connect
    * timeout a controller thread is executed. The controller thread attempts
    * to create a new socket within the given limit of time. If socket
    * constructor does not return until the timeout expires, the controller
    * terminates and throws an {@link ConnectTimeoutException}
    * /p
    *
    * @param host
    * the host name/IP
    * @param port
    * the port on the host
    * @param clientHost
    * the local host name/IP to bind the socket to
    * @param clientPort
    * the port on the local machine
    * @param params
    * {@link HttpConnectionParams Http connection parameters}
    *
    * @return Socket a new socket
    * @throws IOException
    * @throws IOException
    * if an I/O error occurs while creating the socket
    * @throws UnknownHostException
    * if the IP address of the host cannot be determined
    */

    public void connect(final String host, final int sport, final String query,
    final HttpConnectionParams params) throws IOException {

    HostnameVerifier hv = new HostnameVerifier() {
    public boolean verify(String arg0, SSLSession arg1) {
    System.out.println("Bartek: Hostname is not matched for cert.");
    return true;
    }
    };
    URL wlsUrl = null;

    wlsUrl = new URL("https", host, Integer.valueOf(sport).intValue(),
    query);
    System.out
    .println(" Trying a new HTTPS connection using WLS client classes - "
    + wlsUrl.toString());
    HttpsURLConnection sconnection = (HttpsURLConnection) wlsUrl
    .openConnection();
    SocketFactory socketfactory = getSSLContext().getSocketFactory();
    /*
    * HttpsURLConnection sconnection = new HttpsURLConnection( wlsUrl);
    */
    sconnection.setHostnameVerifier(hv);
    //sconnection.setSSLSocketFactory((SSLSocketFactory) socketfactory);
    sconnection.setSSLSocketFactory((SSLSocketFactory) socketfactory);

    //sconnection.setHostnameVerifier(hv);

    tryConnection(sconnection, System.out);
    }

    public static void tryConnection(HttpsURLConnection connection,
    OutputStream stream) throws IOException {
    connection.connect();

    String responseStr = "\t\t" + connection.getResponseCode() + " -- "
    + connection.getResponseMessage() + "\n\t\t"
    + connection.getContent().getClass().getName() + "\n";
    connection.disconnect();
    System.out.print(responseStr);
    }

    }

    Message was edited by:
    herbatniczek

    DB:2.93:How To Use Custom Truststore? 3a

    Case 3 above is completely insecure, and its getAcceptedIssuers() method doesn't obey the specification.

  • RELEVANCY SCORE 2.92

    DB:2.92:Why Remotecertificate Parameter Is Empty In Localcertificateselectioncallback Method? 7c


    Hi.i want to setup a SSL connection in .NET 4.0 , but really don't know everything about SSL handshake rules and life cycle. i wrote a code

    void main()
    {
    TcpClient client = new TcpClient(192.168.1.160, 4113);
    SslStream sslStream = new SslStream(
    client.GetStream(),
    false,
    new RemoteCertificateValidationCallback(ValidateServerCertificate),
    new LocalCertificateSelectionCallback(localCertSelection)
    );
    sslStream.AuthenticateAsClient(serverName);
    }

    public X509Certificate localCertSelection(object sender, string targetHost, X509CertificateCollection localCertificates, X509Certificate remoteCertificate, string[] acceptableIssuers)
    {// why here remoteCertificate parameter is empty? acceptableIssuers and localCertificates too
    string cert = MIIEwjCCA6qgAwIBAgIBADANBgkqhkiG9w...;
    X509Certificate clientCert = new X509Certificate(System.Text.Encoding.ASCII.GetBytes(cert));
    return clientCert;
    }

    public bool ValidateServerCertificate(
    object sender,
    X509Certificate certificate,
    X509Chain chain,
    SslPolicyErrors sslPolicyErrors)
    {
    // certificate has data now. it has come from server
    if (sslPolicyErrors == SslPolicyErrors.None) return true;
    return false;
    }

    DB:2.92:Why Remotecertificate Parameter Is Empty In Localcertificateselectioncallback Method? 7c

    Hi.i want to setup a SSL connection in .NET 4.0 , but really don't know everything about SSL handshake rules and life cycle. i wrote a code

    void main()
    {
    TcpClient client = new TcpClient(192.168.1.160, 4113);
    SslStream sslStream = new SslStream(
    client.GetStream(),
    false,
    new RemoteCertificateValidationCallback(ValidateServerCertificate),
    new LocalCertificateSelectionCallback(localCertSelection)
    );
    sslStream.AuthenticateAsClient(serverName);
    }

    public X509Certificate localCertSelection(object sender, string targetHost, X509CertificateCollection localCertificates, X509Certificate remoteCertificate, string[] acceptableIssuers)
    {// why here remoteCertificate parameter is empty? acceptableIssuers and localCertificates too
    string cert = MIIEwjCCA6qgAwIBAgIBADANBgkqhkiG9w...;
    X509Certificate clientCert = new X509Certificate(System.Text.Encoding.ASCII.GetBytes(cert));
    return clientCert;
    }

    public bool ValidateServerCertificate(
    object sender,
    X509Certificate certificate,
    X509Chain chain,
    SslPolicyErrors sslPolicyErrors)
    {
    // certificate has data now. it has come from server
    if (sslPolicyErrors == SslPolicyErrors.None) return true;
    return false;
    }

  • RELEVANCY SCORE 2.92

    DB:2.92:Pem Encoded Certificate zx


    I have code ( see below ) which is successfully generating a Self Signed certificate in PEM format using the Bouncy Castle libraries.

    I'm not sure how to directly generate the cert in PEM format, ...the generated cert is in DER format and the extra code you see is to convert it to PEM. I have verified that the certificate works by running the openssl command :

    openssl x509 -in certificatename.pem -text

    The problem I am having is that openssl does not like the private key. Note in the code that I convert the private key I used to generate the certificate to PEM format - I use the very same technique as that used for the certificate. The following openssl command says that there is a problem with the private key:

    openssl rsa -in privatekeyname.pem -text

    Does anyone know how to generate either the certificate, private key or both directly in PEM format or what I may be doing wrong ? See code below:

    =================================================================================
    private X509Certificate buildSelfSignedCert(int keyLen, String associatedOrg) {

    // Security constants

    X509Certificate X509certificate = null;
    String ecnryptionType = "MD5WithRSAEncryption";
    String keyGeneratorType = "RSA";
    String LF = "\n";
    String beginCertificate = "-----BEGIN CERTIFICATE-----" +LF;
    String endCertificate = "-----END CERTIFICATE-----" +LF;
    String beginRSAPrivateKey = "-----BEGIN RSA PRIVATE KEY-----" +LF;
    String endRSAPrivateKey = "-----END RSA PRIVATE KEY-----" +LF;

    // Init a security provider

    Security.addProvider(new BouncyCastleProvider());

    // Generate key pair

    try {

    // Pub / Private key stuff
    KeyPairGenerator keyGen =
    KeyPairGenerator.getInstance( keyGeneratorType);
    keyGen.initialize(keyLen, new SecureRandom());

    KeyPair keypair = keyGen.generateKeyPair();
    PrivateKey prikey = keypair.getPrivate();
    PublicKey pubkey = keypair.getPublic();

    // Init values for cert
    Calendar dateThen = Calendar.getInstance();
    dateThen.add(Calendar.YEAR, 1);

    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    certGen.setSerialNumber(BigInteger.valueOf(1));
    certGen.setIssuerDN(new X509Principal(associatedOrg));
    certGen.setNotBefore(new Date());
    certGen.setNotAfter(new Date(dateThen.getTimeInMillis()));
    certGen.setSubjectDN(new X509Principal(associatedOrg));
    certGen.setPublicKey(pubkey);
    certGen.setSignatureAlgorithm(ecnryptionType);

    // Create Cert
    X509certificate = certGen.generateX509Certificate(prikey);

    // Persist Cert
    try {

    // Write cert in PEM ( Base64 ) format - each line 64 bytes
    FileOutputStream fos = new FileOutputStream("CERT.pem");
    fos.write(beginCertificate.getBytes());

    byte [] certb64 = Base64.encode(X509certificate.getEncoded());

    int length = certb64.length;
    int bytestowrite = 64;

    for ( int written = 0; written length; ) {
    fos.write(certb64,written,bytestowrite);
    fos.write(LF.getBytes());
    written+=bytestowrite;
    if ( (length - written) 64 ) {
    bytestowrite=(length - written);
    }
    } // for ( int written = 0; written length; )

    fos.write(endCertificate.getBytes());
    fos.close();

    // Write Private Key in PEM ( Base64 ) format
    certb64 = null;

    fos = new FileOutputStream("prikey.pem");
    fos.write(beginRSAPrivateKey.getBytes());

    certb64 = Base64.encode(prikey.getEncoded());

    length = certb64.length;
    bytestowrite = 64;

    for ( int written = 0; written length; ) {
    fos.write(certb64,written,bytestowrite);
    fos.write(LF.getBytes());
    written+=bytestowrite;
    if ( (length - written) 64 ) {
    bytestowrite=(length - written);
    }
    } // for ( int written = 0; written length; )

    fos.write(endRSAPrivateKey.getBytes());
    fos.close();

    } catch (IOException ex) {

    } catch (CertificateEncodingException ex) {

    }

    } catch (java.security.NoSuchAlgorithmException x) {

    } catch (java.security.SignatureException x) {

    } catch (java.security.InvalidKeyException x) {

    }

    return X509certificate;
    }

    DB:2.92:Pem Encoded Certificate zx

    Hi, i have a similar problem with BouncyCastle and openssl PEM functions; so, i 'm found that normally BC lib creates RSA key encoded (padded) with PKCS#8 spec.; instead openssl is able to read only PKCS#1 padded keys; fortunately openssl can convert PKCS#8 key using command:

    openssl pkcs8 -in "pk-pkcs8.pem" -out "pk.key" -nocrypt

    important: the original (BC created) pk PEM file need to start with -----BEGIN PRIVATE KEY----- only ("...BEGIN RSA PRIVATE KEY..." is not good....)

    the converted file, "pk.key" in the example, is now in the right format for openssl functions....

    ...but, i'm another problem now: merging the PK PEM file converted with corresponding X509 certificate PEM (Base64) encoded, to obtain a complete certificate PEM description (adding also the HD section on the bottom, like openssl documentation example), i've tried to use it in Apache modssl module, but openssl response is always "key mismatch"...

    suggestions ?

    thnx

  • RELEVANCY SCORE 2.89

    DB:2.89:Accessing Client Certificate From Portlet aa


    I am relatively new to JDeveloper and Portlet development and am trying to figure out how to access a client certificate from a portlet. I have successfully retrieved information from the client certificate from a webcenter application using HttpServletRequest within a java class as follows...

    FacesContext facesContext = FacesContext.getCurrentInstance();
    HttpServletRequest request = (HttpServletRequest)facesContext.getExternalContext().getRequest();

    *if (request.isSecure()) {*
    X509Certificate[] cert = (X509Certificate[])request.getAttribute("javax.servlet.request.X509Certificate");

    *...*

    However, I have read that HttpServletRequest, by design, is no longer available within a portlet. I am currently using JDeveloper 11.1.1.3 and the IntegratedWebLogicServer configured for Two-Way SSL. I have tried using the PortletRequest...

    FacesContext facesContext = FacesContext.getCurrentInstance();
    ExternalContext externalContext = facesContext.getExternalContext();
    PortletRequest portletReq = (PortletRequest)externalContext.getRequest();

    *if (portletReq.isSecure()) {*

    PortletSession portletSession = (PortletSession)externalContext.getSession(false);
    X509Certificate[] cert = (X509Certificate[])portletSession.getAttribute("javax.servlet.request.X509Certificate", PortletSession.APPLICATION_SCOPE);

    *....*

    When I get an Enumeration of the portletReq.getAttributeNames() and print them out, I do not see a certificate attribute name. As it stands now, I cannot get the portletReq.isSecure() to evaluate to true. So, I am not even sure I am getting a valid request. Thanks in advance to anyone who can provide insight into how I can get to the client certificate from a portlet.

    DB:2.89:Accessing Client Certificate From Portlet aa

    Yes. I am only deploying to the IntegratedWebLogicServer at this time.

  • RELEVANCY SCORE 2.87

    DB:2.87:Ambiguity In Certificate Validation Path Construction z1


    Hello,
    I have two "root" certificates. Both have the same public key. The second one have certificate policy restriction. So when I manually find the certificatiion path for an end user certificate the path is uniquely defined. The same result give me Windows.
    When I use java.security.cert.CertPathValidator this class randomly detect anchors (path). One time to the first root, next time to the second root. I think there is a bug in the jdk or I do something wrong.

    I've also tries to explicitly set
    pkixParameters.setPolicyMappingInhibited(false);
    pkixParameters.setPolicyQualifiersRejected(true);
    but nothing helped.

    Details: The "root" certs are
    * http://xien.jikos.cz/czp/ICA_Czech.der
    * http://xien.jikos.cz/czp/ICA_Slovak.der
    ICA_Slovak.der has the same public key included as the ICA_Czech.der. ICA_Slovak.der is signed by http://xien.jikos.cz/czp/NBU_Slovak.der - National Security Agency in the Slovak Republic.

    Both certificates are from www.ica.cz certification authority. ICA comes from Czech Rep. and has opened its office in the Slovak Rep. So this is a real case, all certificates can be downloaded from TSL list, see http://ec.europa.eu/information_society/policy/esignature/eu_legislation/trusted_lists/index_en.htm

    I have an end user certificate:
    * http://xien.jikos.cz/czp/Bc.%20Konvalinka.der
    When I try construct a certificate path I get ambiguousresults. With the same inputs the results differ. One call returns different results than the next call.
    I find the path in two steps:

    1. Recursively find parent:

    public ListX509Certificate getValidationPath(KeyStore keyStore, X509Certificate cert)
    throws Exception {
    ArrayListX509Certificate path = new ArrayListX509Certificate();

    TrustAnchor trustedAnchor = null;
    while (cert!=null) {
    trustedAnchor = getTrustedAnchor(keyStore, cert);
    if ( trustedAnchor==null
    || trustedAnchor.getTrustedCert()==null
    || trustedAnchor.getTrustedCert().equals(cert)) {
    break;
    }
    cert = trustedAnchor.getTrustedCert();
    path.add(cert);
    }

    return path;
    }2. Find the parent:

    public TrustAnchor getTrustedAnchor(KeyStore keyStore, X509Certificate cert) throws Exception {
    if (keyStore.size() == 0) {
    throw new PathValidationException("KeyStore is empty, cannot continue");
    }

    CertificateFactory fact = CertificateFactory.getInstance("X.509", CertTool.PROVIDER_DEFAULT);

    PKIXParameters pkixParameters = new PKIXParameters(keyStore);
    pkixParameters.setRevocationEnabled(false);
    pkixParameters.setDate(cert.getNotAfter());
    CertPath certPath = fact.generateCertPath(Collections.singletonList(cert));
    CertPathValidator validator = CertPathValidator.getInstance("PKIX", CertTool.PROVIDER_DEFAULT);

    PKIXCertPathChecker checker602 = new IgnoreCriricalPathChecker();
    ArrayListPKIXCertPathChecker checkers = new ArrayListPKIXCertPathChecker();
    checkers.add(checker602);
    pkixParameters.setCertPathCheckers(checkers);

    pkixParameters.setPolicyMappingInhibited(false);
    pkixParameters.setPolicyQualifiersRejected(true);

    PKIXCertPathValidatorResult result = null;
    TrustAnchor trustAnchor = null;
    try {
    result = (PKIXCertPathValidatorResult) validator.validate(certPath, pkixParameters);
    trustAnchor = result.getTrustAnchor();
    if (trustAnchor == null) {
    log.error("Parentcert wasn't found for: " + cert + ", " + Utils.bytesToBase64(cert.getEncoded()));
    }
    } catch (CertPathValidatorException ex) {
    log.error("Parent cert wasn't found for: " + cert + ", " + Utils.bytesToBase64(cert.getEncoded()));
    }

    return trustAnchor;
    }As a provider I've used "SUN" or "BC" with the same bad results.
    Can anybody help?

    Thanks.
    Jan Vavra

    Edited by: jan.vavra on 14.7.2011 0:57

    DB:2.87:Ambiguity In Certificate Validation Path Construction z1

    Is there an other way how to use java crypto to build cert path?
    The piece of code I've posted is only for verification the path not for building?

    I'm writing software that validates certs against the TSL list. So I cannot ignore certs of CAs from the TSL.

  • RELEVANCY SCORE 2.84

    DB:2.84:Why Are Not The Certificate Valid? sm


    Hey!I have installed a root certificate in the trusted root on my computer(Windows XP), when my application tries to connect to a webservice(that runs SSL security(https)) it fails becourse of the SSL certificate.If I build my own CertificateHandler like this :public class CetificateHandler : System.Net.ICetificatePolicy{
    public CertificateHandler() {}public bool CheckValidationResult(ServicePoint sp, X509Certificate cert, WebRequest req, int problem){
    return true;

    DB:2.84:Why Are Not The Certificate Valid? sm

    SnowJim said:So you mean that I can´t loop through the certirficate in my X509Store(X509Store(StoreName.Root, StoreLocation.LocalMachine)) and compare it with the one that I get from the service that I tries to communicate with?

  • RELEVANCY SCORE 2.83

    DB:2.83:Formatted Elements Of The Signature c1


    Hi..

    when I sign doc, the element content X509Certificate out justifiy.
    ex:
    X509Certificate
    asdfasfsdfqwrg
    asdfasfsadfasf
    asdfdferwerqer
    asdfafafafafafsf
    /X509CertificateBut need that it has left but in a line
    thus:

    X509Certificate
    asdfasfsdfqwrgasdfasfsadfasfasdfdferwerqerasdfafafafafafsf
    /X509Certificateusing org.apache.xml.security.signature.XMLSignature

    X509Certificate cert = (X509Certificate)certF.generateCertificate(fileCertificado);
    org.apache.xml.security.signature.XMLSignature sig = new org.apache.xml.security.signature.XMLSignature(doc, file.toURI().toString(), org.apache.xml.security.signature.XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1);

    nfe.appendChild(sig.getElement());

    Transforms transforms = new Transforms(doc);
    transforms.addTransform("http://www.w3.org/2000/09/xmldsig#enveloped-signature");
    transforms.addTransform("http://www.w3.org/TR/2001/REC-xml-c14n-20010315");

    sig.addDocument("#"+idNota, transforms, org.apache.xml.security.utils.Constants.ALGO_ID_DIGEST_SHA1);

    sig.addKeyInfo(cert);
    sig.sign(privateKey);

    DB:2.83:Formatted Elements Of The Signature c1

    Hi..

    when I sign doc, the element content X509Certificate out justifiy.
    ex:
    X509Certificate
    asdfasfsdfqwrg
    asdfasfsadfasf
    asdfdferwerqer
    asdfafafafafafsf
    /X509CertificateBut need that it has left but in a line
    thus:

    X509Certificate
    asdfasfsdfqwrgasdfasfsadfasfasdfdferwerqerasdfafafafafafsf
    /X509Certificateusing org.apache.xml.security.signature.XMLSignature

    X509Certificate cert = (X509Certificate)certF.generateCertificate(fileCertificado);
    org.apache.xml.security.signature.XMLSignature sig = new org.apache.xml.security.signature.XMLSignature(doc, file.toURI().toString(), org.apache.xml.security.signature.XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1);

    nfe.appendChild(sig.getElement());

    Transforms transforms = new Transforms(doc);
    transforms.addTransform("http://www.w3.org/2000/09/xmldsig#enveloped-signature");
    transforms.addTransform("http://www.w3.org/TR/2001/REC-xml-c14n-20010315");

    sig.addDocument("#"+idNota, transforms, org.apache.xml.security.utils.Constants.ALGO_ID_DIGEST_SHA1);

    sig.addKeyInfo(cert);
    sig.sign(privateKey);

  • RELEVANCY SCORE 2.82

    DB:2.82:How I Can Read Pem, Der And P12 Files Into A X509certificate? ap


    Hi
    Does pem, der and p12 files are readable by java code?
    Can I read them into a X509certificate?
    Can you peleas leave some tips?

    Thanks

  • RELEVANCY SCORE 2.81

    DB:2.81:Can Not Get The Alias Of A Cert From Usb-Key By Sunmscapi And Csp xa


    Hi:

    I'm using "SunMSCAPI"(jdk1.6.0_12) to access certificate and key in windows certificate store. The certificate and key are registered to windows by a self-defined CSP and a self-defined register program from a USB-key, and they can be accessed by CAPICOM or by cryptoAPI. But the following java program can not access the certificate . The java program below may be right, as it can access the certificate and key registered to windows from a PFX file. While the java program cannot get the "alias" of the USB-key's certificate.

    Is there any problem with the self-defined CSP or the self-defined register program, or both? What is wrong? Thanks a lot!

    --------------------------------------------------------------------------------------------------------------------------------------------------

    import java.security.KeyStore;
    import java.security.KeyStoreException;
    import java.security.Provider;
    import java.security.Security;
    import java.security.cert.X509Certificate;
    import java.util.ArrayList;
    import java.util.Enumeration;
    import java.util.List;

    public class IECertificateLoader {
    private KeyStore keystore = null;

    public Provider getKeyStoreProvider() {
    return Security.getProvider("SunMSCAPI");
    }

    public KeyStore load(Object ... params){
    KeyStore ieKeyStore = null;
    try {
    ieKeyStore = KeyStore.getInstance("Windows-My");
    ieKeyStore.load(null, null);
    } catch (Exception e) {
    e.printStackTrace();
    }
    this.keystore = ieKeyStore;
    return ieKeyStore;
    }

    public ListX509Certificate getCertificates() {
    if(keystore == null){
    throw new RuntimeException("KeyStore is not initialized.");
    }
    return getCertificates(keystore);
    }

    private ListX509Certificate getCertificates(KeyStore keystore){
    ListX509Certificate list = new ArrayListX509Certificate();
    try {
    EnumerationString enu = keystore.aliases();
    while(enu.hasMoreElements()){
    String alias = enu.nextElement(); // Can not get the alias of the certificate in USB-key !!!
    X509Certificate cert = (X509Certificate)keystore.getCertificate(alias);
    if(cert != null){
    list.add(cert);
    }
    }
    } catch (KeyStoreException e) {
    e.printStackTrace();
    }
    return list;
    }

    public static void main(String[] args){
    IECertificateLoader loader = new IECertificateLoader();
    loader.load();
    ListX509Certificate certs = loader.getCertificates();
    for(X509Certificate xcert:certs){
    System.out.println("=="+xcert.getSubjectDN());
    }

    }
    }

    DB:2.81:Can Not Get The Alias Of A Cert From Usb-Key By Sunmscapi And Csp xa

    Hi:

    I'm using "SunMSCAPI"(jdk1.6.0_12) to access certificate and key in windows certificate store. The certificate and key are registered to windows by a self-defined CSP and a self-defined register program from a USB-key, and they can be accessed by CAPICOM or by cryptoAPI. But the following java program can not access the certificate . The java program below may be right, as it can access the certificate and key registered to windows from a PFX file. While the java program cannot get the "alias" of the USB-key's certificate.

    Is there any problem with the self-defined CSP or the self-defined register program, or both? What is wrong? Thanks a lot!

    --------------------------------------------------------------------------------------------------------------------------------------------------

    import java.security.KeyStore;
    import java.security.KeyStoreException;
    import java.security.Provider;
    import java.security.Security;
    import java.security.cert.X509Certificate;
    import java.util.ArrayList;
    import java.util.Enumeration;
    import java.util.List;

    public class IECertificateLoader {
    private KeyStore keystore = null;

    public Provider getKeyStoreProvider() {
    return Security.getProvider("SunMSCAPI");
    }

    public KeyStore load(Object ... params){
    KeyStore ieKeyStore = null;
    try {
    ieKeyStore = KeyStore.getInstance("Windows-My");
    ieKeyStore.load(null, null);
    } catch (Exception e) {
    e.printStackTrace();
    }
    this.keystore = ieKeyStore;
    return ieKeyStore;
    }

    public ListX509Certificate getCertificates() {
    if(keystore == null){
    throw new RuntimeException("KeyStore is not initialized.");
    }
    return getCertificates(keystore);
    }

    private ListX509Certificate getCertificates(KeyStore keystore){
    ListX509Certificate list = new ArrayListX509Certificate();
    try {
    EnumerationString enu = keystore.aliases();
    while(enu.hasMoreElements()){
    String alias = enu.nextElement(); // Can not get the alias of the certificate in USB-key !!!
    X509Certificate cert = (X509Certificate)keystore.getCertificate(alias);
    if(cert != null){
    list.add(cert);
    }
    }
    } catch (KeyStoreException e) {
    e.printStackTrace();
    }
    return list;
    }

    public static void main(String[] args){
    IECertificateLoader loader = new IECertificateLoader();
    loader.load();
    ListX509Certificate certs = loader.getCertificates();
    for(X509Certificate xcert:certs){
    System.out.println("=="+xcert.getSubjectDN());
    }

    }
    }

  • RELEVANCY SCORE 2.81

    DB:2.81:Why Unable To Get Client Certificate Serial Number? 1c



    I am using mod_jk 1.2 with JBoss bundle and Apache2.I am follow the instruction from JBoss wiki http://www.jboss.org/wiki/Wiki.jsp?page=UsingMod_jk1.2WithJBoss, and it workable.However, the problem which I meet now is I am not able to get the Client Cert's serial number from my Java code. It return "Object was null".My code----------------------------------Object o = request.getAttribute("javax.servlet.request.X509Certificate");if (o != null) { X509Certificate certs[] = (X509Certificate[])o; X509Certificate cert = certs[0]; //Get the Serial Number of the digital certs. serialNumBig = cert.getSerialNumber(); serialNum = serialNumBig.intValue(); System.out.println("Serial Number: "+ serialNum);} else { System.out.println("Object was null.");}-----------------------------------I try to get configure SSL enable in JBoss without link and using with Apache2. It able to get the Client Cert's serial number.May I know which part I had miss out? Anybody able to give me some advice?Thank you.

    DB:2.81:Why Unable To Get Client Certificate Serial Number? 1c


    Hi, I'm having the same issue. How did you solve it? Can't figure out how to setup Apache mod_jk + ajp13 + client cert chain. Looking in the mod_jk.log in the debug mode. I have the following log: The interesting thing is that the mod_jk doesn't send the whole certificate, it seems to truncate it. Why does the mod_jk does it? Is it misconfigured?[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] uri_worker_map_update::jk_uri_worker_map.c (786): File /etc/httpd/conf/uriworkermap.properties is not modified[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] map_uri_to_worker::jk_uri_worker_map.c (678): Found session identifier ';jsessionid=rkx1vvqyIC4B9H24XVEogA**.node1' in url '/consignacao/inicial.do;jsessionid=rkx1vvqyIC4B9H24XVEogA**.node1'[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] map_uri_to_worker::jk_uri_worker_map.c (682): Attempting to map URI '/consignacao/inicial.do' from 10 maps[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] find_match::jk_uri_worker_map.c (503): Attempting to map context URI '/internet_base/*=loadbalancer' source 'uriworkermap'[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] find_match::jk_uri_worker_map.c (503): Attempting to map context URI '/jmx-console/*=loadbalancer' source 'uriworkermap'[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] find_match::jk_uri_worker_map.c (503): Attempting to map context URI '/web-console/*=loadbalancer' source 'uriworkermap'[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] find_match::jk_uri_worker_map.c (503): Attempting to map context URI '/consignacao/*=loadbalancer' source 'uriworkermap'[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] find_match::jk_uri_worker_map.c (516): Found a wildchar match '/consignacao/*=loadbalancer'[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] jk_handler::mod_jk.c (2222): Into handler jakarta-servlet worker=loadbalancer r-proxyreq=0[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] wc_get_worker_for_name::jk_worker.c (115): found a worker loadbalancer[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] wc_maintain::jk_worker.c (323): Maintaining worker loadbalancer[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] maintain_workers::jk_lb_worker.c (556): decay with 2^95[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] wc_get_name_for_type::jk_worker.c (292): Found worker type 'lb'[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] init_ws_service::mod_jk.c (775): SSL client certificate (5558 bytes): -----BEGIN CERTIFICATE-----MIIFsjCCBJqgAwIBAgIERDVUhDANBgkqhkiG9w0BAQUFADBwMQswCQYDVQQGEwJCUjETMBEGA1UEChMKSUNQLUJyYXNpbDE1MDMGA1UECxMsQXV0b3JpZGFkZSBDZXJ0...skiping the whole certificate...Hcr23ijE9hMUvHrKpIQgHb6xIUa5WUFW1er+ms4ViuDgZSHWuwIi3dhXGlaLWkahmGkm/0/nH+fd5KAK4tR234nc6iZ5Dg==-----END CERTIFICATE----------BEGIN CERTIFICATE-----MIIFlTCCBH2gAwIBAgISMjAwNjA0MDcxNTM2NDYwMDAxMA0GCSqGSIb3DQEBBQUAMFAxCzAJBgNVBAYTAkJSMRMwEQYDVQQKEwpJQ1AtQnJhc2lsMSwwKgYDVQQDEyNB...skiping the whole certificate...YaAQAK0TZ14JCLipeAnivAoR+7OsIT9gk6JF+C2fQDkAWd/GX+PPsnSGJvUntoz/CKCkL+YS/e1kh3EqUMEXYmTKZm9lwDpzZSPVdpRieCqQNtcjXm5R2L8=-----END CERTIFICATE----------BEGIN CERTIFICATE-----MIIEODCCAyCgAwIBAgIBFTANBgkqhkiG9w0BAQUFADCBtDELMAkGA1UEBhMCQlIxEzARBgNVBAoTCklDUC1CcmFzaWwxPTA7BgNVBAsTNEluc3RpdHV0byBOYWNpb25h...skiping the whole certificate...Kr1tz8mC+Wd8WR8ieeWwcEDt7frV1vXHSeqA8n0QwaNWfYneDWqklcr7Z9Z6bu6ByQfHRF6V/bSFpw6nZkYHZs7JO3w+3wmyJvc7Tg==-----END CERTIFICATE-----[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] init_ws_service::mod_jk.c (888): Service protocol=HTTP/1.1 method=GET host=(null) addr=10.8.1.74 name=www.trt9.gov.br port=8443 auth=(null) user=(null) laddr=10.1.2.62 raddr=10.8.1.74 uri=/consignacao/inicial.do;jsessionid=rkx1vvqyIC4B9H24XVEogA**.node1[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] service::jk_lb_worker.c (940): service sticky_session=1 id='rkx1vvqyIC4B9H24XVEogA**.node1'[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] service::jk_lb_worker.c (962): service worker=node1 route=node1[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] ajp_get_endpoint::jk_ajp_common.c (2579): acquired connection pool slot=0[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] ajp_marshal_into_msgb::jk_ajp_common.c (553): ajp marshaling done[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] ajp_service::jk_ajp_common.c (2050): processing node1 with 2 retries[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] ajp_send_request::jk_ajp_common.c (1352): (node1) all endpoints are disconnected, detected by connect check (0), cping (0), send (0)[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] jk_open_socket::jk_connect.c (448): socket TCP_NODELAY set to On[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] jk_open_socket::jk_connect.c (548): trying to connect socket 19 to 10.1.2.62:8009[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] jk_open_socket::jk_connect.c (574): socket 19 connected to 10.1.2.62:8009[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] ajp_connect_to_endpoint::jk_ajp_common.c (878): Connected socket 19 to (10.1.2.62:8009)[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] ajp_connection_tcp_send_message::jk_ajp_common.c (934): sending to ajp13 pos=4 len=6047 max=8192[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] ajp_connection_tcp_send_message::jk_ajp_common.c (934): 0000 12 34 17 9B 02 02 00 08 48 54 54 50 2F 31 2E 31 - .4......HTTP/1.1[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] ajp_connection_tcp_send_message::jk_ajp_common.c (934): 0010 00 00 41 2F 63 6F 6E 73 69 67 6E 61 63 61 6F 2F - ..A/consignacao/[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] ajp_connection_tcp_send_message::jk_ajp_common.c (934): 0020 69 6E 69 63 69 61 6C 2E 64 6F 3B 6A 73 65 73 73 - inicial.do;jsess[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] ajp_connection_tcp_send_message::jk_ajp_common.c (934): 0030 69 6F 6E 69 64 3D 72 6B 78 31 76 76 71 79 49 43 - ionid=rkx1vvqyIC[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] ajp_connection_tcp_send_message::jk_ajp_common.c (934): 0040 34 42 39 48 32 34 58 56 45 6F 67 41 2A 2A 2E 6E - 4B9H24XVEogA**.n[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] ajp_connection_tcp_send_message::jk_ajp_common.c (934): 0050 6F 64 65 31 00 00 09 31 30 2E 38 2E 31 2E 37 34 - ode1...10.8.1.74[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] ajp_connection_tcp_send_message::jk_ajp_common.c (934): 0060 00 FF FF 00 0F 77 77 77 2E 74 72 74 39 2E 67 6F - .....www.trt9.go[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] ajp_connection_tcp_send_message::jk_ajp_common.c (934): 0070 76 2E 62 72 00 20 FB 01 00 08 A0 01 00 03 2A 2F - v.br..........*/[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] ajp_connection_tcp_send_message::jk_ajp_common.c (934): 0080 2A 00 00 0F 41 63 63 65 70 74 2D 4C 61 6E 67 75 - *...Accept-Langu...[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] ajp_connection_tcp_send_message::jk_ajp_common.c (934): 0190 31 00 07 15 B6 2D 2D 2D 2D 2D 42 45 47 49 4E 20 - 1....-----BEGIN.[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] ajp_connection_tcp_send_message::jk_ajp_common.c (934): 01a0 43 45 52 54 49 46 49 43 41 54 45 2D 2D 2D 2D 2D - CERTIFICATE-----[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] ajp_connection_tcp_send_message::jk_ajp_common.c (934): 01b0 0A 4D 49 49 46 73 6A 43 43 42 4A 71 67 41 77 49 - .MIIFsjCCBJqgAwI[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] ajp_connection_tcp_send_message::jk_ajp_common.c (934): 01c0 42 41 67 49 45 52 44 56 55 68 44 41 4E 42 67 6B - BAgIERDVUhDANBgk...[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] ajp_connection_tcp_send_message::jk_ajp_common.c (934): 03e0 42 42 51 41 44 67 59 30 41 4D 49 47 4A 41 6F 47 - BBQADgY0AMIGJAoG[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] ajp_connection_tcp_send_message::jk_ajp_common.c (934): 03f0 42 41 4E 4B 39 2F 79 2B 42 0A 49 65 4A 51 59 57 - BANK9/y+B.IeJQYW[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] ajp_send_request::jk_ajp_common.c (1395): (node1) request body to send 0 - request body to resend 0[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] ajp_connection_tcp_get_message::jk_ajp_common.c (1117): received from ajp13 pos=0 len=47 max=8192[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] ajp_connection_tcp_get_message::jk_ajp_common.c (1117): 0000 04 02 57 00 19 46 61 6C 68 61 20 69 6E 65 73 70 - ..W..Falha.inesp[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] ajp_connection_tcp_get_message::jk_ajp_common.c (1117): 0010 65 72 61 64 61 20 6E 6F 20 6C 6F 67 69 6E 00 00 - erada.no.login..[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] ajp_connection_tcp_get_message::jk_ajp_common.c (1117): 0020 01 A0 01 00 09 74 65 78 74 2F 68 74 6D 6C 00 00 - .....text/html..[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] ajp_unmarshal_response::jk_ajp_common.c (608): status = 599[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] ajp_unmarshal_response::jk_ajp_common.c (615): Number of headers is = 1[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] ajp_unmarshal_response::jk_ajp_common.c (671): Header[0] [Content-Type] = [text/html][Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] ajp_connection_tcp_get_message::jk_ajp_common.c (1117): received from ajp13 pos=0 len=1173 max=8192[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] ajp_connection_tcp_get_message::jk_ajp_common.c (1117): 0000 03 04 91 0D 0A 0D 0A 3C 21 44 4F 43 54 59 50 45 - .......!DOCTYPE[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] ajp_connection_tcp_get_message::jk_ajp_common.c (1117): 0010 20 68 74 6D 6C 0D 0A 50 55 42 4C 49 43 20 22 2D - .html..PUBLIC."-[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] ajp_connection_tcp_get_message::jk_ajp_common.c (1117): 0020 2F 2F 57 33 43 2F 2F 44 54 44 20 58 48 54 4D 4C - //W3C//DTD.XHTML[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] ajp_connection_tcp_get_message::jk_ajp_common.c (1117): 0030 20 31 2E 30 20 54 72 61 6E 73 69 74 69 6F 6E 61 - .1.0.Transitiona[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] ajp_connection_tcp_get_message::jk_ajp_common.c (1117): 0040 6C 2F 2F 45 4E 22 0D 0A 22 68 74 74 70 3A 2F 2F - l//EN".."http://[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] ajp_connection_tcp_get_message::jk_ajp_common.c (1117): 0050 77 77 77 2E 77 33 2E 6F 72 67 2F 54 52 2F 78 68 - www.w3.org/TR/xh[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] ajp_connection_tcp_get_message::jk_ajp_common.c (1117): 0060 74 6D 6C 31 2F 44 54 44 2F 78 68 74 6D 6C 31 2D - tml1/DTD/xhtml1-[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] ajp_connection_tcp_get_message::jk_ajp_common.c (1117): 0070 74 72 61 6E 73 69 74 69 6F 6E 61 6C 2E 64 74 64 - transitional.dtd[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] ajp_connection_tcp_get_message::jk_ajp_common.c (1117): 0080 22 3E 0D 0A 0D 0A 3C 68 74 6D 6C 3E 0D 0A 09 3C - "...........[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] ws_write::mod_jk.c (455): written 1169 out of 1169[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] ajp_connection_tcp_get_message::jk_ajp_common.c (1117): received from ajp13 pos=0 len=4 max=8192[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] ajp_connection_tcp_get_message::jk_ajp_common.c (1117): 0000 03 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 - ................[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] ajp_connection_tcp_get_message::jk_ajp_common.c (1117): received from ajp13 pos=0 len=2 max=8192[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] ajp_connection_tcp_get_message::jk_ajp_common.c (1117): 0000 05 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 - ................[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] ajp_process_callback::jk_ajp_common.c (1661): AJP13 protocol: Reuse is OK[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] ajp_reset_endpoint::jk_ajp_common.c (691): (node1) resetting endpoint with sd = 19[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] ajp_done::jk_ajp_common.c (2522): recycling connection pool slot=0 for worker node1[Wed Jan 23 19:35:22 2008]loadbalancer www.trt9.gov.br 0.018127[Wed Jan 23 19:35:22 2008][12604:3086853840] [debug] jk_handler::mod_jk.c (2348): Service finished with status=599 for worker=loadbalancerThanks,Rafael

  • RELEVANCY SCORE 2.80

    DB:2.80:Encrypt Data By .Net And Decrypt By Java Problem 7d


    Hi all,

    I am trying to envelop the data using the public key in the certificate and then encode it using Base64 string.
    However, the file generated cannot be decrypted by our partner which uses JAVA IAIK-JCE object to encrypt/decrypt.

    Here is my .Net code :
    public string Encrypt(byte[] data, X509Certificate2 cert)
    {
    string resultStr = "";

    if (data == null)
    throw new ArgumentNullException("data");

    if (cert == null)
    throw new ArgumentNullException("certificate");

    ContentInfo content = new ContentInfo(data);
    AlgorithmIdentifier alg = new AlgorithmIdentifier(new Oid("1.2.840.113549.3.7")); // 3des
    EnvelopedCms envelopedCms = new EnvelopedCms(content, alg);
    CmsRecipient cmsreceipient = new CmsRecipient(SubjectIdentifierType.IssuerAndSerialNumber, cert);
    envelopedCms.Encrypt(cmsreceipient)
    byte[] result = envelopedCms.Encode();
    resultStr = Convert.ToBase64String(result, Base64FormattingOptions.InsertLineBreaks);
    return resultStr;
    }Here is the Java code :
    public String encrypt(byte data2BeEncrypted[], byte bank_certificate[])
    {
    EnvelopedData enveloped_data = null;
    RecipientInfo recipients[] = new RecipientInfo[1];
    X509Certificate bank_X509_certificate = new X509Certificate(bank_certificate);
    recipients[0] = new RecipientInfo(bank_X509_certificate, AlgorithmID.rsaEncryption);
    enveloped_data = new EnvelopedData(data2BeEncrypted, AlgorithmID.des_EDE3_CBC);
    enveloped_data.setRecipientInfos(recipients);
    String encoded_enveloped_data = null;
    encoded_enveloped_data = new String(Util.Base64Encode(enveloped_data.getEncoded()));
    if(enveloped_data == null || encoded_enveloped_data == null)
    return null;
    return encoded_enveloped_data;
    }The exception in decryption from the JAVA program.

    iaik.asn1.DerInputException: Next ASN.1 object is no INTEGER!

    DB:2.80:Encrypt Data By .Net And Decrypt By Java Problem 7d

    Hi all,

    I am trying to envelop the data using the public key in the certificate and then encode it using Base64 string.
    However, the file generated cannot be decrypted by our partner which uses JAVA IAIK-JCE object to encrypt/decrypt.

    Here is my .Net code :
    public string Encrypt(byte[] data, X509Certificate2 cert)
    {
    string resultStr = "";

    if (data == null)
    throw new ArgumentNullException("data");

    if (cert == null)
    throw new ArgumentNullException("certificate");

    ContentInfo content = new ContentInfo(data);
    AlgorithmIdentifier alg = new AlgorithmIdentifier(new Oid("1.2.840.113549.3.7")); // 3des
    EnvelopedCms envelopedCms = new EnvelopedCms(content, alg);
    CmsRecipient cmsreceipient = new CmsRecipient(SubjectIdentifierType.IssuerAndSerialNumber, cert);
    envelopedCms.Encrypt(cmsreceipient)
    byte[] result = envelopedCms.Encode();
    resultStr = Convert.ToBase64String(result, Base64FormattingOptions.InsertLineBreaks);
    return resultStr;
    }Here is the Java code :
    public String encrypt(byte data2BeEncrypted[], byte bank_certificate[])
    {
    EnvelopedData enveloped_data = null;
    RecipientInfo recipients[] = new RecipientInfo[1];
    X509Certificate bank_X509_certificate = new X509Certificate(bank_certificate);
    recipients[0] = new RecipientInfo(bank_X509_certificate, AlgorithmID.rsaEncryption);
    enveloped_data = new EnvelopedData(data2BeEncrypted, AlgorithmID.des_EDE3_CBC);
    enveloped_data.setRecipientInfos(recipients);
    String encoded_enveloped_data = null;
    encoded_enveloped_data = new String(Util.Base64Encode(enveloped_data.getEncoded()));
    if(enveloped_data == null || encoded_enveloped_data == null)
    return null;
    return encoded_enveloped_data;
    }The exception in decryption from the JAVA program.

    iaik.asn1.DerInputException: Next ASN.1 object is no INTEGER!

  • RELEVANCY SCORE 2.78

    DB:2.78:Consume Java Web Service With Ws-Security j9


    All,
    I'm struggling to find .NET code that consumes a Java web service that has WS-Security enabled. The requestexample.xml I was given looks like this:
    ?xml version=1.0 encoding=UTF-8?
    SOAP-ENV:Envelope xmlns:SOAP-ENV=http://schemas.xmlsoap.org/soap/envelope/ xmlns:jeesa=http://disnoss.disa.mil/jeesa
    SOAP-ENV:Header
    wsse:Security xmlns:wsse=http://oasis-200401-wss-wssecurity-secext-1.0.xsd
    SOAP-ENV:mustUnderstand=1
    wsse:BinarySecurityToken xmlns:wsu=http://oasis-200401-wss-wssecurity-utility-1.0.xsd

    EncodingType=http://oasis-200401-wss-soap-message-security-1.0#Base64Binary

    ValueType=http://oasis-200401-wss-x509-token-profile-1.0#X509v3

    wsu:Id=CertId-1440871VALUE
    /wsse:BinarySecurityToken
    ds:Signature xmlns:ds=http://www.w3.org/2000/09/xmldsig# Id=Signature-28113457
    ds:SignedInfo
    ds:CanonicalizationMethod Algorithm=http://www.w3.org/2001/10/xml-exc-c14n#/ds:CanonicalizationMethod
    ds:SignatureMethod Algorithm=http://www.w3.org/2000/09/xmldsig#dsa-sha1/ds:SignatureMethod
    ds:Reference URI=#id-9434319
    ds:Transforms
    ds:Transform Algorithm=http://www.w3.org/2001/10/xml-exc-c14n#/ds:Transform
    /ds:Transforms
    ds:DigestMethod Algorithm=http://www.w3.org/2000/09/xmldsig#sha1/ds:DigestMethod
    ds:DigestValueVALUE/ds:DigestValue
    /ds:Reference
    /ds:SignedInfo
    ds:SignatureValueVALUE/ds:SignatureValue
    ds:KeyInfo Id=KeyId-VALUE
    wsse:SecurityTokenReference xmlns:wsu=http://oasis-200401-wss-wssecurity-utility-1.0.xsd wsu:Id=STRId-26009930wsse:Reference URI=#CertId-1440871 ValueType=http://oasis-200401-wss-x509-token-profile-1.0#X509v3/wsse:Reference/wsse:SecurityTokenReference
    /ds:KeyInfo
    /ds:Signature/wsse:Security
    /SOAP-ENV:Header
    SOAP-ENV:Body xmlns:wsu=http://oasis-200401-wss-wssecurity-utility-1.0.xsd wsu:Id=id-9434319
    jeesa:PodStatusRequest
    jeesa:serviceDutyLocationNameVALUE/jeesa:serviceDutyLocationName
    /jeesa:PodStatusRequest
    /SOAP-ENV:Body
    /SOAP-ENV:Envelope

    I've run the wsdl and schema through wsdl.exe to create my proxy service, and wrote some the following code that isn't working:
    ServiceAvailabilityWebService wsService = new ServiceAvailabilityWebService();
    wsService.SoapVersion = System.Web.Services.Protocols.SoapProtocolVersion.Default;
    wsService.Proxy.Credentials =

    X509Certificate xCert = new X509Certificate();
    xCert = X509Certificate.CreateFromCertFile(C:\\Certs\\Filename.cer);
    wsService.ClientCertificates.Add(xCert);

    PodStatusRequestType oPodStatusRequest = new PodStatusRequestType();
    PodStatusResponseType oPodStatusResponse = new PodStatusResponseType();

    oPodStatusRequest.Item = ServiceDutyLocation;
    oPodStatusResponse.podStatusList = wsService.getPodStatus(oPodStatusRequest).podStatusList;

    Console.WriteLine(oPodStatusResponse.podStatusList);
    Console.ReadLine();
    This is in a console app for testing (it will end up in a SharePoint Timer Job). The response I get is The request failed with an empty response, which suggests the request
    was refused.
    I'm not sure if the problem is the cert stuff or not.Any help is appreciated.

    DB:2.78:Consume Java Web Service With Ws-Security j9

    I got past this to this problem instead: http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/3bf97e80-9828-45e8-8366-53850e49a46d

  • RELEVANCY SCORE 2.77

    DB:2.77:Security Cert Expired zf



    Both Google Chrome and Firefox complain about the security cert for pingsso has expired.

    Someone has fallen asleep at their desk?




    --Claude

  • RELEVANCY SCORE 2.75

    DB:2.75:Signing Xml Documents With Right Keyinfo Block jd


    Hello, I'm trying to get right formatted x509 signature block for my xml file. It's like this
    KeyInfo
    X509Data
    X509Certificate
    /X509Certificate
    /X509Data
    X509IssuerSerial
    X509IssuerName
    X509IssuerName
    /X509IssuerName
    X509SerialNumber
    /X509SerialNumber
    /X509IssuerName
    /X509IssuerSerial
    /KeyInfo
    But when I add code(cert is X509certificate2):
    KeyInfo ki = new KeyInfo();
    KeyInfoX509Data keyInfoData = new KeyInfoX509Data(cert);
    keyInfoData.AddIssuerSerial(cert.Issuer, cert.GetSerialNumberString());
    ki.AddClause(keyInfoData);
    format is like thile this:
    KeyInfo
    X509Data
    X509IssuerSerial
    X509IssuerName/X509IssuerName
    X509SerialNumber/X509SerialNumber
    /X509IssuerSerial
    X509Certificate
    /X509Certificate
    /X509Data
    /KeyInfo
    Is there easy way to get issuerserial out of x509data-section? I have tried to create two x509data-tags, but then format is different. Thank you for help Matti

    DB:2.75:Signing Xml Documents With Right Keyinfo Block jd

    Hello Kurt! Thank you for reply :) I got example from applicationrequest what have this uppest format. They said request is used in their messages. I paste signature part this:
    Signature xmlns=http://www.w3.org/2000/09/xmldsig#
    SignedInfo
    CanonicalizationMethod Algorithm=http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments/
    SignatureMethod Algorithm=http://www.w3.org/2000/09/xmldsig#rsa-sha1/
    Reference URI=
    Transforms
    Transform Algorithm=http://www.w3.org/2000/09/xmldsig#enveloped-signature/
    /Transforms
    DigestMethod Algorithm=http://www.w3.org/2000/09/xmldsig#sha1/
    DigestValuePkNgWl1Tqr1D2YddYKA4a95XcNs=/DigestValue
    /Reference
    /SignedInfo
    SignatureValueOoAzRt70BLo2baxrQOoBXmuObrUMaHRdnxFW0bmT1yQyYjJhq2T7OaE8vhnYAoj25Eel5R7REZgF
    keUmI+758hi80tA/wyNQF8RDnvPOOWj/rtlSS1iNdIt3L9C8kthIQrvpmJZS9zUO4KJArEQ0bCrA
    XImcXgwTI99HKla2tuU=/SignatureValue
    KeyInfo
    X509Data
    X509CertificateMIIEnjCCA4agAwIBAgICIWAwDQYJKoZIhvcNAQEFBQAwcTELMAkGA1UEBhMCU0UxHjAcBgNVBAoT
    FU5vcmRlYSBCYW5rIEFCIChwdWJsKTEsMCoGA1UEAxMjTm9yZGVhIFRlc3Qgcm9sZS1jZXJ0aWZp
    Y2F0ZXMgQ0EgMDExFDASBgNVBAUTCzUxNjQwNi0wMTIwMB4XDTA3MDMwODEyMTIzN1oXDTA5MDMw
    ODEyMTIzN1owZjELMAkGA1UEBhMCU0UxGjAYBgNVBAMMEVRlc3QgV2Vic2VydmljZSAzMQowCAYD
    VQQEDAEzMRgwFgYDVQQqDA9UZXN0IFdlYnNlcnZpY2UxFTATBgNVBAUTDDAwOTU1NzE5MjI0MzCB
    nzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAj0afTNWopnu1uJHnYup1MimpOv5FkOtU99w+88y7
    xItb+8Mtt2L/1OK6Jky5g1/PKzqfRiz1x6nDMw5v/495s4F3MQO67t0TPdHnNU3PFJAhTkZr17pO
    DUvO2fd/QDiRLzaTk+nVWuPgCrRab2vRuTXDgcXRMpRA5eng5rRBY/cCAwEAAaOCAc0wggHJMAkG
    A1UdEwQCMAAwEQYDVR0OBAoECEFcbFxpPw9/MBMGA1UdIAQMMAowCAYGKoVwRwEDMBMGA1UdIwQM
    MAqACELAuvRkyFBRMA4GA1UdDwEB/wQEAwIFoDCCAW0GA1UdHwSCAWQwggFgMIGtoIGqoIGnhoGk
    bGRhcDovLzEwLjE2Mi4xMDQuNDMvY249Tm9yZGVhJTIwVGVzdCUyMHJvbGUtY2VydGlmaWNhdGVz
    JTIwQ0ElMjAwMSxvPU5vcmRlYSUyMEJhbmslMjBBQiUyMChwdWJsKSxjPVNFP2NlcnRpZmljYXRl
    cmV2b2NhdGlvbmxpc3QgZm9yIGFueSByZWFzb24uIChOb3QgbGlzdGVkIGluIENSTCkwga2ggaqg
    gaeGgaRsZGFwOi8vMTAuMTYyLjEwNC40My9jbj1Ob3JkZWElMjBUZXN0JTIwcm9sZS1jZXJ0aWZp
    Y2F0ZXMlMjBDQSUyMDAxLG89Tm9yZGVhJTIwQmFuayUyMEFCJTIwKHB1YmwpLGM9U0U/Y2VydGlm
    aWNhdGVyZXZvY2F0aW9ubGlzdCBmb3IgYW55IHJlYXNvbi4gKE5vdCBsaXN0ZWQgaW4gQ1JMKTAN
    BgkqhkiG9w0BAQUFAAOCAQEAAj+zNWRgJN212cgydeL1RnR/6rFi15s+y4uBMnT5utQ7A6Zb/7dZ
    FWxGwGUIQUM8SDotHH3EPvDvZFW0JxVJlyzpec9kE+N9P317YLYMwE6QtAyyP2kFre7StUu2WxgX
    SKfYNCYn5H3K0Tur12ayZWA+WDBzJJ24GMvCga72Q7edMAbc3Ko09KrnVW/I868p/JWGB2p8DT18
    l6RLpIjSI1Xgkh2QielQaV5opaqQ5VHdJN8rz1BZ3e+eO5JPEhOfqpJpYukgfeyktMMxJMcWIxwn
    4TvdFF6Rtvz4Hca6xt//xNuu9F0nIz70xfL8M5TI0IhFataIwon+WJfJ7VyOjw==/X509Certificate
    /X509Data
    X509IssuerSerial
    X509IssuerName(I removed this)/X509IssuerName
    X509SerialNumber8544/X509SerialNumber
    /X509IssuerSerial
    /KeyInfo
    /Signature
    I have used p12-certificatefile for getting signature. It's secured with password. I only wonder can I use as you mentioned with same results. Thank you! Matti

  • RELEVANCY SCORE 2.74

    DB:2.74:A Question About Certificate z7


    Hello everyone, i am a newbie here. i just wrote a little code trying to create a X.509 certificate, but it can not be executed, and i do not understand the reason. I appreciate if anyone can give me some help. thank you very much.
    here is the code:

    import java.security.cert.*;
    import java.io.*;

    public class certi {
    public static void main(String[ ] args) throws FileNotFoundException, CertificateException, IOException {
    InputStream inStream = new FileInputStream ("fileName-of-cert.txt");
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    X509Certificate cert = (X509Certificate)cf.generateCertificate(inStream);
    inStream.close();
    }
    }

    and this is the comment given by the java interpreter:

    Exception in thread "main" java.security.cert.CertificateException: Could not pa
    rse certificate: java.io.IOException: DerInputStream.getLength(): lengthTag=127,
    too big.
    at sun.security.provider.X509Factory.engineGenerateCertificate(Unknown S
    ource)
    at java.security.cert.CertificateFactory.generateCertificate(Unknown Sou
    rce)
    at certi.main(certi.java:8)
    Caused by: java.io.IOException: DerInputStream.getLength(): lengthTag=127, too b
    ig.
    at sun.security.util.DerInputStream.getLength(Unknown Source)
    at sun.security.util.DerValue.init(Unknown Source)
    at sun.security.util.DerValue.init(Unknown Source)
    ... 3 more

    DB:2.74:A Question About Certificate z7

    You need to use the BouncyCastle class
    X509CertificateGenerator, for instance.

    Please download the full BouncyCastle package
    (crypto-123.tar.gz) and read the test programs.

    By the way, usually you use some Certificate Server
    software (like Microsoft, SunONE, Entrust or OpenSSL,
    or even Sun's keytool) to generate the X.509
    certificates for you. It is easier and safer. You can
    get sample certificates at the Entrust or Verisign
    sites.please read the question "trying to get a free .cer from verisign" which i just post

  • RELEVANCY SCORE 2.74

    DB:2.74:Ssl Problems, Exception: A Call To Sspi Failed ax


    Hi!
    I have been trying to build a very simple client-server system that uses SSL.
    However, when i run the program the AuthenticateAsServer() in the server throws an AuthenticationException which says that A call to SSPI failed.
    The inner exception is a Win32Exception saying that Local Security Authority (LSA) could not be contacted.
     
    The code, copied from some website and slightly modified, looks like:
     
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Net.Security;
    using System.Net;
    using System.Net.Sockets;
    using System.IO;
    using System.Security.Cryptography.X509Certificates;
    using System.Security.Authentication;
    namespace Server
    {

    class Program
    {

    static void Main(string[] args)
    {

    X509Certificate cert = getServerCert();
    TcpListener sslServer = new TcpListener(IPAddress.Any, 4242);
    sslServer.Start();
    Console.WriteLine(Waiting for incoming connection...);
    TcpClient client = sslServer.AcceptTcpClient();
    SslStream sslStream = new SslStream(client.GetStream());
    try
    {

    // *** this method throws exception ***
    sslStream.AuthenticateAsServer(cert, false, SslProtocols.Tls, false);
    }
    catch (AuthenticationException e)
    {

    Console.WriteLine(Exception: {0} {1} {2}, e.GetType(), e.Message, e.GetBaseException());

    Console.WriteLine(Authentication failed - closing the connection.);
    sslStream.Close();
    client.Close();
    return;
    }
    StreamReader reader = new StreamReader(sslStream);
    StreamWriter writer = new StreamWriter(sslStream);

    }
     

    private static X509Certificate getServerCert()
    {

    X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
    store.Open(OpenFlags.ReadOnly);

    Console.WriteLine(Store name: {0}, store.Name);
    Console.WriteLine(Store location: {0}, store.Location);

    X509CertificateCollection cert = store.Certificates.Find(X509FindType.FindBySubjectName, SslStreamCert, true);
    foreach (X509Certificate x509 in cert)
    {

    Console.WriteLine(certificate name: {0}, x509.Subject);
    }

    return cert[0];
    }

    }
    }
     
     
    Anyone have ANY clues about this?
    I have spent the last three days with this problem and appreciate ANY help!!!
     
    //
    Björn

    DB:2.74:Ssl Problems, Exception: A Call To Sspi Failed ax

    hai,
    I am trying to the same simple ssl client server apllication and uses the same code and got same error.Would you get any solution to rectify that?if so please help me to rectify the error.
     
    is there any other way to do the ssl application.
     
    awaiting for the solution.
     
    thanks,
    akila
     
     

  • RELEVANCY SCORE 2.74

    DB:2.74:Apache+Ssl(Ubuntu10) 1x


    Please, help me connect with SSL in javaME. Server apache2. OS UBUNTU 10.

    I do this:

    -------------------- create my CA, sign server and client side with my CA -----------------
    cd /home/work/keystores

    --- create my CA---
    openssl genrsa -des3 -out ca.key 2048
    openssl req -new -x509 -days 365 -key ca.key -out ca.crt

    -- create server certificate ---
    openssl genrsa -des3 -out server.key 2048
    openssl req -new -key server.key -out server.csr
    openssl x509 -req -days 365 -in server.csr -CA ca.crt -CAkey ca.key -set_serial 01 -out server.crt

    -- remove passwords for apache ---
    openssl rsa -in server.key -out server.key.insecure
    mv server.key server.key.secure
    mv server.key.insecure server.key

    sudo cp server.key /etc/apache2/ssl
    sudo cp server.crt /etc/apache2/ssl

    --- import root ca into keystore ---
    keytool -import -trustcacerts -alias cacert -file ca.crt -keystore keystore.jks
    keytool -genkey -alias my -keyalg RSA -keystore keystore.jks -keysize 2048

    --- generate csr ---
    keytool -certreq -alias my -keystore keystore.jks -file my.csr

    ---sign with CA
    openssl x509 -req -days 365 -in my.csr -CA ca.crt -CAkey ca.key -set_serial 01 -out my.crt

    ---import certificate into keystore ---
    keytool -import -trustcacerts -alias my -file my.crt -keystore keystore.jks
    ------------------------------------------------------------------------------------------------------------

    apache starts successfully, virtual host(myhostname.com) opening

    I'm testing in emulator:

    Trying sign midlet with my.crt - can't connect.

    Trying code:

    [code=java]
    CertStore cs = new CertStore() {
    public X509Certificate[] getCertificates(String arg0) {
    Logger.debug("get certificates");

    try {
    X509Certificate[] certs = new X509Certificate[1];
    InputStream is = this.getClass().getResourceAsStream("/my.crt");
    Logger.debug("inputStream: " + is);
    byte[] buffer = new byte[is.available()];
    is.read(buffer);
    Logger.debug("cert length: " + buffer.length);
    certs[0] = X509Certificate.generateCertificate(buffer, 0, buffer.length);
    return certs;
    } catch (Exception ex) {
    Logger.error("can't open resource");
    ex.printStackTrace();
    return null;
    }
    }
    };
    SSLStreamConnection.setTrustedCertStore(cs);
    Logger.debug("Before opening ssl connection" );

    // Here exception: Certificate was issued by an unrecognized entity
    SSLStreamConnection sslscon = new SSLStreamConnection("myhostname.com", 443, connection.openInputStream(), connection.openOutputStream());

    Logger.debug("trusted certstore: " + cs.getCertificates(null));
    OutputStream outputStream = sslscon.openOutputStream();
    writer = new OutputStreamWriter(outputStream, "UTF-8");
    writer.write(data.toString());
    writer.close();
    outputStream.close();

    DB:2.74:Apache+Ssl(Ubuntu10) 1x

    Please, help me connect with SSL in javaME. Server apache2. OS UBUNTU 10.

    I do this:

    -------------------- create my CA, sign server and client side with my CA -----------------
    cd /home/work/keystores

    --- create my CA---
    openssl genrsa -des3 -out ca.key 2048
    openssl req -new -x509 -days 365 -key ca.key -out ca.crt

    -- create server certificate ---
    openssl genrsa -des3 -out server.key 2048
    openssl req -new -key server.key -out server.csr
    openssl x509 -req -days 365 -in server.csr -CA ca.crt -CAkey ca.key -set_serial 01 -out server.crt

    -- remove passwords for apache ---
    openssl rsa -in server.key -out server.key.insecure
    mv server.key server.key.secure
    mv server.key.insecure server.key

    sudo cp server.key /etc/apache2/ssl
    sudo cp server.crt /etc/apache2/ssl

    --- import root ca into keystore ---
    keytool -import -trustcacerts -alias cacert -file ca.crt -keystore keystore.jks
    keytool -genkey -alias my -keyalg RSA -keystore keystore.jks -keysize 2048

    --- generate csr ---
    keytool -certreq -alias my -keystore keystore.jks -file my.csr

    ---sign with CA
    openssl x509 -req -days 365 -in my.csr -CA ca.crt -CAkey ca.key -set_serial 01 -out my.crt

    ---import certificate into keystore ---
    keytool -import -trustcacerts -alias my -file my.crt -keystore keystore.jks
    ------------------------------------------------------------------------------------------------------------

    apache starts successfully, virtual host(myhostname.com) opening

    I'm testing in emulator:

    Trying sign midlet with my.crt - can't connect.

    Trying code:

    [code=java]
    CertStore cs = new CertStore() {
    public X509Certificate[] getCertificates(String arg0) {
    Logger.debug("get certificates");

    try {
    X509Certificate[] certs = new X509Certificate[1];
    InputStream is = this.getClass().getResourceAsStream("/my.crt");
    Logger.debug("inputStream: " + is);
    byte[] buffer = new byte[is.available()];
    is.read(buffer);
    Logger.debug("cert length: " + buffer.length);
    certs[0] = X509Certificate.generateCertificate(buffer, 0, buffer.length);
    return certs;
    } catch (Exception ex) {
    Logger.error("can't open resource");
    ex.printStackTrace();
    return null;
    }
    }
    };
    SSLStreamConnection.setTrustedCertStore(cs);
    Logger.debug("Before opening ssl connection" );

    // Here exception: Certificate was issued by an unrecognized entity
    SSLStreamConnection sslscon = new SSLStreamConnection("myhostname.com", 443, connection.openInputStream(), connection.openOutputStream());

    Logger.debug("trusted certstore: " + cs.getCertificates(null));
    OutputStream outputStream = sslscon.openOutputStream();
    writer = new OutputStreamWriter(outputStream, "UTF-8");
    writer.write(data.toString());
    writer.close();
    outputStream.close();

  • RELEVANCY SCORE 2.73

    DB:2.73:Java Verification Of A Ruby Signature 11


    Hi,

    This is not strictly a Java question but more related to interoperability with Ruby. I'm generating a public certificate and a private key using Ruby (and reusing what already works in Rubygems) and using the private key to sign some data. I then use the public certificate in Java to verify the signature.

    The signature itself is read correctly in Java, however I've found it impossible to have the signature verification working. Note that verification works perfectly in Ruby. Anybody has an idea of what I'm doing wrong?

    Build the keys in Ruby:

    Gem::Security::build_self_signed_cert("foo@bar.com",
    {:save_cert_path="public-cert.pem", :save_key_path="private-key.pem"})

    Sign some text content in Ruby:

    content = "some text"
    signer = Gem::Security::Signer.new("private-key.pem", ["public-cert.pem"])
    cert_chain = signer.cert_chain.map { |cert| cert.to_s }
    dgst_algo = Gem::Security::OPT[:dgst_algo]
    dgst = dgst_algo.digest(content)
    sig = signer.sign(dgst)

    Try to validate in Java:

    String signedData = "some text";
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    X509Certificate cert = (X509Certificate) cf
    .generateCertificate(new BufferedInputStream(new FileInputStream("public-cert.pem")));
    String algorithm = cert.getSigAlgName();
    Signature signature = Signature.getInstance(algorithm);
    signature.initVerify(cert);
    signature.update(signedData.getBytes());
    signature.verify(signatureData); // = false

    Thanks for any help!

    Matthieu

    DB:2.73:Java Verification Of A Ruby Signature 11

    MatthieuRiou wrote:
    As you can see it's strictly identical except that Java bytes are signed. So is the sign a potential problem? I could make sure those are all positive by sticking them in a short but down the road, Signature works on bytes anyway.Whether the bytes are signed or unsigned is irrelevant since they are not used in arithmetic. Only the bit pattern matters and they are the same.

  • RELEVANCY SCORE 2.72

    DB:2.72:X509 -≫ X509certificate Conversion j3


    Hi all,
    I'm trying to convert a X509 certificate read from the ServletRequest to a
    standard java X509Certificate but I alway get the following exception:

    java.security.cert.CertificateParsingException: signed fields overrun
    at sun.security.x509.X509CertImpl.parse(X509CertImpl.java:1036)
    at sun.security.x509.X509CertImpl.init(X509CertImpl.java:150)
    at
    sun.security.provider.X509Factory.engineGenerateCertificate(X509Factory.java
    :93)
    ...

    This is the code:

    X509[] acert = null;
    X509Certificate cert = null;

    acert =
    (X509[])request.getAttribute("javax.net.ssl.peer_certificates");

    byte[] receivedCert = acert[0].getBytes();
    ByteArrayInputStream bais = new ByteArrayInputStream(receivedCert);
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    cert = cf.generateCertificate(bais);

    The last line is the one that trows the exception. Does anyone have any idea
    about what I'm doing wrong?

    Thank you.
    Milko

    DB:2.72:X509 -≫ X509certificate Conversion j3

    I am facing the exact same problem. Found any solution yet ?To reformulate my problem : how is it possible to access non-standard parameters of a certificate from a servlet in weblogic?It is surprising for weblogic not to provide such a feature. Why not provide a class that could be X509Certificate compliant ?Please help !Yann.

  • RELEVANCY SCORE 2.72

    DB:2.72:Convert To Iaik.X509.X509certificate? Urgent, Please Help. dm


    Hi,

    Anyone knows the way to convert from a "java.security.cert.X509Certificate" certificate to a "iaik.x509.X509Certificate" one. Please advice?

    Thanks in advance.

    DB:2.72:Convert To Iaik.X509.X509certificate? Urgent, Please Help. dm

    Hi,

    Anyone knows the way to convert from a "java.security.cert.X509Certificate" certificate to a "iaik.x509.X509Certificate" one. Please advice?

    Thanks in advance.

  • RELEVANCY SCORE 2.71

    DB:2.71:Sha256 Certificate ks


    Hi all,i'd like to check (on Windows XP SP2, .NET 1.1), if my X509-Certifcate is SHA256-Certifcate.I try to use the following:{ cert = new CAPICOM.CertificateClass(); cert.Load("my_cert.cer",null, CAPICOM.CAPICOM_KEY_STORAGE_FLAG.CAPICOM_KEY_STORAGE_DEFAULT, CAPICOM.CAPICOM_KEY_LOCATION.CAPICOM_CURRENT_USER_KEY); string sr = cert.Export(CAPICOM.CAPICOM_ENCODING_TYPE.CAPICOM_ENCODE_BASE64);X509Certificate c1 = new X509Certificate(Convert.FromBase64String(sr));}The Property c1.GetKeyAlgorithm() is "1.2.840.113549.1.1.1" what means "RSA encryption" and NOT1.2.840.113549.1.1.11" what I'm expecting.Where I'm wrong?Thanks a lot,Alex

    DB:2.71:Sha256 Certificate ks

    Greetings, Link is given below. http://www.obviex.com/samples/Code.aspx?Source=HashCSTitle=Hashing%20DataLang=C%23 Take Care PL

  • RELEVANCY SCORE 2.71

    DB:2.71:What Does "Certificateparsingexception: Signed Fields Invalid" Mean? 39


    Hello,

    The following code generates a java.security.cert.CertificateParsingException: signed fields invalid exception:

    URL url = new URL("http://hostname/TemporaryKey.pfx");
    InputStream inStream = url.openStream();
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    *exception occurs here==X509Certificate cert = (X509Certificate)cf.generateCertificate(inStream);
    inStream.close();The name for the .pfx file was changed but is valid.

    Any suggestions?

    Thanks,
    williamj

  • RELEVANCY SCORE 2.71

    DB:2.71:Access To Starkey Usb Token (Safesign) With Pkcs11 Java xk


    Hello guys,

    iam trying to access my StarKey USB Token with Java using PKCS11.
    I've already read the guide under http://docs.oracle.com/javase/1.5.0/docs/guide/security/p11guide.html and it still doesnt work.

    I tried following codings:
    Coding 1:_
    -----------------------------------------------------------------------------
    +public static void main(String[] args) throws InterruptedException {+

    +//Load the implementation of PKCS11+
    String pkcs11ConfigFile = "C:\\Users\\*******\\pksc11.cfg";
    Provider pkcs11Provider = new sun.security.pkcs11.SunPKCS11(pkcs11ConfigFile);

    Security.addProvider(pkcs11Provider);

    +//PIN is used to protect the information strored in the card+
    char [] pin = {'1', '2', '3', '4'};

    +try {+

    +//Load KeyStore+

    System.out.println(KeyStore.getDefaultType());
    KeyStore smartCardKeyStore = KeyStore.getInstance("PKCS11",pkcs11Provider);

    smartCardKeyStore.load(null, pin);

    +//Get the enumeration of the entris in the keystore+
    Enumeration aliasesEnum = smartCardKeyStore.aliases();
    +while (aliasesEnum.hasMoreElements()) {+

    +//Print alias+
    String alias = (String) aliasesEnum.nextElement();
    System.out.println("Alias: " alias);+
    +//Print certificate+
    X509Certificate cert = (X509Certificate) smartCardKeyStore.getCertificate(alias);
    System.out.println("Certificate: " cert);+
    +//Print public key+
    PublicKey publicKey = cert.getPublicKey();
    System.out.println("Public key: " publicKey);+
    +//Print private key+
    PrivateKey privateKey = (PrivateKey) smartCardKeyStore.getKey(alias, null);
    System.out.println("Private key: " privateKey);+
    +//Encryption/Decryption Test+
    byte[] plainText = new String("Hello World!").getBytes();
    byte[] cipherText = privateEncrypt(plainText, privateKey);
    System.out.println("Cipher Text: " byte2hex(cipherText));+
    byte[] decryptedText = publicDecrypt(cipherText, publicKey);
    System.out.println("Decrypted Text: " new String(decryptedText));+

    +}+
    +} catch (Exception e) {+
    e.printStackTrace();
    +}+
    +}+

    -------------------------------------------------------------
    Getting following error:
    no such algorithm: PKCS11 for provider SunPKCS11-SafeSign
    or if i remove provider from :
    KeyStore smartCardKeyStore = KeyStore.getInstance("PKCS11",pkcs11Provider); to -- KeyStore smartCardKeyStore = KeyStore.getInstance("PKCS11");
    i get following error:
    PKCS11 KeyStore not available

    My pksc11.cfg looks like this:
    name = SafeSign
    library = c:\windows\system32\aetpkss1.dll
    -------------------------------------------------------------
    -------------------------------------------------------------
    -------------------------------------------------------------

    Coding 2:*
    If i use certgate_p11.dll instead of aetpkss1.dll
    i get:
    Exception in thread "main" java.security.ProviderException: Initialization failed
    +at sun.security.pkcs11.SunPKCS11.init(SunPKCS11.java:374)+
    +at sun.security.pkcs11.SunPKCS11.init(SunPKCS11.java:103)+
    +at ShowCardContents.main(ShowCardContents.java:24)+
    Caused by: sun.security.pkcs11.wrapper.PKCS11Exception: CKR_FUNCTION_FAILED
    +at sun.security.pkcs11.wrapper.PKCS11.C_Initialize(Native Method)+
    +at sun.security.pkcs11.wrapper.PKCS11$SynchronizedPKCS11.C_Initialize(PKCS11.java:1484)+
    +at sun.security.pkcs11.wrapper.PKCS11.getInstance(PKCS11.java:156)+
    +at sun.security.pkcs11.SunPKCS11.init(SunPKCS11.java:329)+
    +... 2 more+

    I hope you can help me.

    thanks

    edit:

    Iam Using Windows7 with admin rights, jdk 1,7 and eclipse-java-indigo-SR1-win32

    Edited by: 944576 on 05.07.2012 01:37

    DB:2.71:Access To Starkey Usb Token (Safesign) With Pkcs11 Java xk

    Hi,if you get initialize error because of jdk 7. jdk7 doesn't support pkcs11 even your reference the pkcs11 library

  • RELEVANCY SCORE 2.70

    DB:2.70:Reading A Pem Ca And Returning A X509 Certificate a1


    Hi all!
    I recieved a method to read a pem file with bouncy castle and retrieve a X509 Certificate, but it doesnt working...

    here is the code:

    private X509Certificate readerPEM(byte[] cert) {

    //Transforma o array de bytes em String
    ByteArrayInputStream btCert = new ByteArrayInputStream(cert);
    String strCert = btCert.toString();

    BufferedReader fRd = new BufferedReader(new StringReader(strCert));
    PEMReader pemRd = new PEMReader(fRd);
    Object o;

    try {

    if ((o = pemRd.readObject()) != null) {
    if (o instanceof X509Certificate) {
    return (X509Certificate) o;

    } else {
    return null;
    }
    }

    } catch (Exception e) {
    return null;
    }

    return null;
    }

    i want to learn the right way of read the pem file...

    thanks all
    Peter

    DB:2.70:Reading A Pem Ca And Returning A X509 Certificate a1

    Try to use this code:

    public boolean readerPEM(String certFile)
    {
    Certificate[] certsAux = new Certificate[10];
    int countCert = 0;

    try
    {
    FileReader fRd = new FileReader(certFile);
    PEMReader pemRd = new PEMReader(fRd, null, "IAIK");
    Object o;

    while ((o = pemRd.readObject()) != null)
    {
    if (o instanceof KeyPair)
    {
    KeyPair pair = (KeyPair)o;
    privateKey = (RSAPrivateKey)pair.getPrivate();
    }
    else if (o instanceof Certificate)
    {
    Certificate cert = (Certificate)o;
    certsAux[cantCert] = cert;
    countCert++;
    }
    else
    {
    }
    }

    if (countCert 0)
    {
    certsSign = new X509Certificate[countCert ];

    for (int i = 0; i countCert ; i++)
    certsSign[i] = (X509Certificate)certsAux;
    }

    return true;
    }
    catch (FileNotFoundException e)
    {
    System.err.println("\tEl archivo (" + arch + ") no existe!");
    e.printStackTrace();

    return false;
    }
    catch (Exception e)
    {
    e.printStackTrace();

    return false;
    }
    }

    Regards
    Alejandro

  • RELEVANCY SCORE 2.70

    DB:2.70:X509 Encoded Certificate - Is It Really Asn.1? m7


    I can get a good Certificate from encoded bytes bcert

    ByteArrayInputStream bis = new ByteArrayInputStream(bcert);
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    X509Certificate cert = (X509Certificate)cf.generateCertificate(bis);

    my question: is an encoded certificate (eg bcert) a good ASN.1 ?

    I cant DeCode with marben nor with codec.sourceforge

    Am I wasting my time looking for an ASN.1 decoder? anyway java decodes the bytes to a certificate just fine.

    DB:2.70:X509 Encoded Certificate - Is It Really Asn.1? m7

    Yes, Certificates are encoded using ASN.1 DER (Distinguished Encoding Rules). There are several good ASN.1 Tools which can encode/decode valid Certificates using various programming languages: Java, C, C++, C# and more. A good list of ASN.1 Tools can be found at http://www.itu.int/ITU-T/asn1/links/index.htm.

    Consider trying a free trial of the OSS ASN.1 Tools which includes ASN.1 Studio, an IDE that allows you to compile ASN.1 specifications and encode/decode messages without writing any code. Go to http://www.oss.com/asn1/products/asn1-download.html to download a free trial.

  • RELEVANCY SCORE 2.70

    DB:2.70:A Call To Sspi Failed, See Inner Exception - The Local Security Authority Cannot Be Contacted 3k


    Hi Gurus,I am having some serious troubles understanding and finding a way around this problem I am having. I will post the exception a bit later, first I want to explain what I am trying to do.I am trying to understand SSL communication using C#.I created a certificate using makecert.exe tool, here is the codemakecert -r -pe -n CN=SslTestCert -ss my serverCert.cer -sr localMachineThen I got some sample code from internet and am trying to work. Code has 2 components a Server and a client.I used the following code to load the certificate on server   string certPath = System.Reflection.Assembly.GetEntryAssembly().Location;brnbsp; Console.WriteLine(Location: + certPath);brnbsp; certPath = Path.GetDirectoryName(certPath); brnbsp; certPath = Path.Combine(certPath, serverCert.cer); brnbsp;  Console.WriteLine(Loading Server Cert From:  + certPath);brnbsp;  X509Certificate serverCert = X509Certificate.CreateFromCertFile(certPath);brnbsp; Console.WriteLine(Loaded SERVER Cert From:  + certPath); 

    DB:2.70:A Call To Sspi Failed, See Inner Exception - The Local Security Authority Cannot Be Contacted 3k

    Thanks a lot Vadym, Here is what was the problem so that if another newbie(like me) ends up looking at this thread...My problem was that I was creating the certificate and then using it which was causing the cert to be an invalid cert, following link provided by Vadym gave a good instruction on how to create a valid serthttp://vadmyst.blogspot.com/2008/06/basics-of-securele-data-exchange-under.htmlOnce I had done that, it passed the first test which is a hand shake.Thanks again. I am not done yet because I am to write an app that will communicate with a web service. I will be back..:-)

  • RELEVANCY SCORE 2.69

    DB:2.69:Keystore Issue? (Windows To Solaris) m1


    I have a simple object to sign an XML document. I built in using Eclispe and it works great on my Windows desktop but when I put it on my server (running as an extension object in Coldfusion 7) I get "*java/security/KeyStore$ProtectionParameter*"

    Since I think it is reasonable to assume that the code itself is portable; I must be dealing with a configuration difference between the two platforms.

    What is (are?) the cause(s) of that error?
    (I did try using the full, explicit path to the keystore file and got the exact same error)

    import java.io.*;
    import org.w3c.dom.*;
    import org.xml.sax.*;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.security.KeyStore;
    import javax.xml.crypto.dsig.*;
    import javax.xml.crypto.dsig.spec.*;
    import javax.xml.crypto.dsig.dom.*;
    import javax.xml.crypto.dsig.keyinfo.*;
    import java.security.cert.X509Certificate;
    import javax.xml.transform.*;
    import javax.xml.transform.dom.*;
    import javax.xml.transform.stream.StreamResult;
    import javax.xml.parsers.DocumentBuilderFactory;

    public class XMLsig {
    public static void main (String argv [])throws Exception {

    }
    public String getSig(String docIn){
    String myXMLdoc = docIn;
    String signedDoc = "";
    Reference ref;
    SignedInfo si;
    KeyStore ks;
    XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");
    try {
    ref = fac.newReference("", fac.newDigestMethod(DigestMethod.SHA1, null),
    Collections.singletonList(fac.newTransform(Transform.ENVELOPED,
    (TransformParameterSpec) null)),null, null);
    si = fac.newSignedInfo(fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE,
    (C14NMethodParameterSpec) null),fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null),
    Collections.singletonList(ref));
    ks = KeyStore.getInstance("JKS");
    ks.load(new FileInputStream("hwvauwd233.jks"), "hwvauwd233".toCharArray());
    KeyStore.PrivateKeyEntry keyEntry = (KeyStore.PrivateKeyEntry) ks.getEntry("hwvauwd233.hud.gov",new KeyStore.PasswordProtection("hwvauwd233".toCharArray()));
    X509Certificate cert = (X509Certificate) keyEntry.getCertificate();
    KeyInfoFactory kif = fac.getKeyInfoFactory();
    ArrayList x509Content = new ArrayList();
    x509Content.add(cert.getSubjectX500Principal().getName());
    x509Content.add(cert);
    X509Data xd = kif.newX509Data(x509Content);
    KeyInfo ki = kif.newKeyInfo(Collections.singletonList(xd));
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    StringReader reader = new StringReader(myXMLdoc);
    InputSource xmlSource = new InputSource(reader);
    Document doc = dbf.newDocumentBuilder().parse(xmlSource);
    reader.close();
    DOMSignContext dsc = new DOMSignContext(keyEntry.getPrivateKey(), doc.getDocumentElement());
    XMLSignature signature = fac.newXMLSignature(si, ki);
    signature.sign(dsc);
    try
    {
    DOMSource domSource = new DOMSource(doc);
    StringWriter writer = new StringWriter();
    StreamResult result = new StreamResult(writer);
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    transformer.transform(domSource, result);
    signedDoc = writer.toString();
    }
    catch(TransformerException ex)
    {
    ex.printStackTrace();
    return null;
    }
    } catch (Throwable t) {
    }
    return signedDoc;
    }
    }

    Edited by: panhandler62 on Nov 30, 2009 8:00 AM

    DB:2.69:Keystore Issue? (Windows To Solaris) m1

    And.. we have a winner -- the CF7 server ships with 1.4 I compiled at that level but that doesn't help much since these are 1.6 classes.

    Gonna have to convince these fols to provide a purpose specific app server (cause upgrading te current one onvolves months of regression testing that no one has time for right now.)

  • RELEVANCY SCORE 2.68

    DB:2.68:Verification Of Challenge Fails. 1a


    Hi All,
    A MS CAPI application creates a nonce/challenge and sends to my java application.
    My java appl. signs the challenge, and sends back to MS CAPI for verification.
    But MS CAPI fails to verify the signature.

    Challenge signing java code is pasted below,
    i am using BouncyCastle provider to extract the PKCS12 certificate from the MS keystore.
    Can somebody help me in figuring out where am I going wrong?

    String res = null;
    Provider provider = new BouncyCastleProvider();
    Security.addProvider(provider);

    char[] passwd = KEY_STORE_PASSWORD.toCharArray();
    KeyStore keyStore = KeyStore.getInstance("PKCS12");

    try {
    FileInputStream fis = new FileInputStream(
    "abc.pfx");

    keyStore.load(fis, passwd);
    fis.close();

    } catch (Exception e) {
    e.printStackTrace();
    }

    Enumeration aliases = keyStore.aliases();
    while (aliases.hasMoreElements()) {
    try {
    String alias = (String) aliases.nextElement();
    X509Certificate cert = (X509Certificate) keyStore
    .getCertificate(alias);

    PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, passwd);

    String hdr = "MIME-Version: 1.0\nContent-Disposition: attachment; filename=\"smime.p7m\"\nContent-Type: application/x-pkcs7-mime; name=\"smime.p7m\"\nContent-Transfer-Encoding: base64\n\n";

    // Create the byte array to hold the data
    byte[] bytes = challenge.getBytes();

    Signature signature = Signature.getInstance("SHA1WithRSA");
    signature.initSign(privateKey);
    signature.update(bytes);

    byte[] response = signature.sign();
    res = Base64.encode(response)+Base64.encode(hdr);

    System.out.println("Response:" + res);
    }catch(Exception e){...}

    DB:2.68:Verification Of Challenge Fails. 1a

    Hi All,
    A MS CAPI application creates a nonce/challenge and sends to my java application.
    My java appl. signs the challenge, and sends back to MS CAPI for verification.
    But MS CAPI fails to verify the signature.

    Challenge signing java code is pasted below,
    i am using BouncyCastle provider to extract the PKCS12 certificate from the MS keystore.
    Can somebody help me in figuring out where am I going wrong?

    String res = null;
    Provider provider = new BouncyCastleProvider();
    Security.addProvider(provider);

    char[] passwd = KEY_STORE_PASSWORD.toCharArray();
    KeyStore keyStore = KeyStore.getInstance("PKCS12");

    try {
    FileInputStream fis = new FileInputStream(
    "abc.pfx");

    keyStore.load(fis, passwd);
    fis.close();

    } catch (Exception e) {
    e.printStackTrace();
    }

    Enumeration aliases = keyStore.aliases();
    while (aliases.hasMoreElements()) {
    try {
    String alias = (String) aliases.nextElement();
    X509Certificate cert = (X509Certificate) keyStore
    .getCertificate(alias);

    PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, passwd);

    String hdr = "MIME-Version: 1.0\nContent-Disposition: attachment; filename=\"smime.p7m\"\nContent-Type: application/x-pkcs7-mime; name=\"smime.p7m\"\nContent-Transfer-Encoding: base64\n\n";

    // Create the byte array to hold the data
    byte[] bytes = challenge.getBytes();

    Signature signature = Signature.getInstance("SHA1WithRSA");
    signature.initSign(privateKey);
    signature.update(bytes);

    byte[] response = signature.sign();
    res = Base64.encode(response)+Base64.encode(hdr);

    System.out.println("Response:" + res);
    }catch(Exception e){...}

  • RELEVANCY SCORE 2.68

    DB:2.68:Certificate Chain With Certificatefactory 9z


    Hi , i want to import the cert chain gived by my CA like keytool.
    I try to explain better:
    When i import the file returned by my CA with keytool,
    the method getCertificateChain(myalias) returns 2 certificates.
    I want to make the same operation using java code:

    FileInputStream fis = new FileInputStream(filename);
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    Collection c = cf.generateCertificates(fis);
    X509Certificate certs = new x509Certificate[c.size()];
    Iterator i = c.iterator();
    while (i.hasNext()) {
    cert[num++] = (X509Certificate)i.next();
    System.out.println(cert);
    }

    But Why the Collection size is 1 ? (I expected 2)
    After when i replace the alias certificate in the keystore ,
    with the method getCertificateChain i obtain only 1 cert.
    Any Ideas....
    How can i import the PKCS#7-formatted certificate reply ?

    DB:2.68:Certificate Chain With Certificatefactory 9z

    This thread is a long dead zombie with little if any chance of getting a response from the original contributors. Please start a new thread.

    I shall lock this thread.

  • RELEVANCY SCORE 2.67

    DB:2.67:Java Equivalent Encryption Code In .Net xf


    Hi Team,
    We have below java based encryption code and it is working absolutely fine. Is there any equivalent in code in .net.
    Encrypting in .net and decryption is happening in the java rest based service.
    Java code:
    private static byte[] getEncryptedValueUsingCertificate(String message) {
    byte[] messageCrypte = null;
    try {
    // Certificate Input Stream
    // LA SSL Certificate to be passed.
    InputStream inStream = new FileInputStream(certificate);

    // X509Certificate created
    CertificateFactory cf = CertificateFactory.getInstance(X.509);
    X509Certificate cert = (X509Certificate) cf.generateCertificate(inStream);
    inStream.close();

    // Getting Public key using Certficate
    PublicKey rsaPublicKey = (PublicKey) cert.getPublicKey();

    Cipher encryptCipher = Cipher.getInstance(RSA/ECB/PKCS1Padding, SunJCE);
    encryptCipher.init(Cipher.ENCRYPT_MODE, rsaPublicKey);

    byte[] messageACrypter = message.getBytes();
    // Encrypted String
    messageCrypte = encryptCipher.doFinal(messageACrypter);
    } catch (Exception e) {
    // TODO: Exception Handling
    e.printStackTrace();
    }
    return messageCrypte;
    }

    DB:2.67:Java Equivalent Encryption Code In .Net xf

    I believe all of these actions are possible to do in .NET. The only thing that I am not familiar with is the use of RSA encryption in .NET code. Here is a link to some information about RSA and .NET:
    http://www.codeproject.com/Articles/10877/Public-Key-RSA-Encryption-in-C-NET

  • RELEVANCY SCORE 2.66

    DB:2.66:Basic Asymmetric Example zj


    Here is a basic example of using public key cryptography correctly. Note this
    does not send a message digest, MAC, or Signature to verify data integrety.
    You may wish to add that.

    char[] passwd = userSuppliedKeyStorePw.toCharArray();

    String keyStoreFile = System.getProperty("user.home") + "/.keystore";
    String trustedCertFile = System.property("java.home") + "/jre/lib/security/cacerts"
    KeyStore ks = KeyStorke.getInstance("JKS");
    ks.load(new FileInputStream(keyStoreFile), passwd);

    SecureRandom rand = new SecureRandom();

    X509Certificate cert = (X509Certificate) ks.getCertificate(recipientAlias);
    cert.checkValidity();
    if(cert.getKeyUsage() != null cert.getKeyUsage()[2] == false)
    throw new RuntimeException("Inappropriate key for key encryption");
    Principal issuer = cert.getIssuerDN();
    ks.load(new FileInputStream(trustedCertFile), null);
    Certificate trustedCert = ks.getCertificate(issuer.getName());
    if(trustedCert == null)
    throw new RuntimeException("Public Key not signed by trusted party!");
    cert.verify(trustedCert.getPublicKey());

    KeyGenerator kGen = KeyGenerator.getInstance("DESede");
    kGen.init(192, rand);
    Key CEK = kGen.generateKey();

    Cipher c = Cipher.getInstance("RSA");
    c.init(Cipher.ENCRYPT_MODE, cert);
    byte[] encCEK = c.doFinal(CEK.getEncoded());

    netWorkStream.writeInt(encCEK.length);
    netWorkStream.flush();
    netWorkStream.write(encCek);
    netWorkStream.flush();

    Cipher cc = Cipher.getInstance("DESede/CBC/PKCS5Padding");
    cc.init(Cipher.ENCRYPT_MODE, CEK, rand);
    AlgorithmParameters params = cc.getParameters();
    byte[] encParams = params.getEncoded();

    netWorkStream.writeInt(encParams.length);
    netWorkStream.flush();
    netWorkStream.write(encParams);
    netWorkStream.flush();

    File f = new File(fileToEncrypt);
    int len = f.length();
    int encLen = ((len / cc.getBlockSize()) + 1) * cc.getBlockSize();
    netWorkStream.writeInt(encLen);
    netWorkStream.flush();

    CipherOutputStream cos = new CipherOutputStream(netWorkStream, cc);
    FileInputStream fis = new FileInputStream(f);
    byte[] buf = new byte[1024];
    while((len = fis.read(buf)) != -1) {
    cos.write(buf, 0, len);
    }
    cos.close();
    fis.close();

    DB:2.66:Basic Asymmetric Example zj

    I hope you're still on th forum. Can you tell me more about the LimitedInputStream class and what class the networkStream variable is?

    We're working with this code and can't seem to get it to work.

    Thx, in advance.

  • RELEVANCY SCORE 2.66

    DB:2.66:Actividentity Client V6.X And Jsp zj


    Our application is not working/responding when we use the ActivIdentity Client V6.x to process/interact with CAC Card (X509) Certification.
    The part of the JSP is failing inside the Jdeveloper is

    X509Certificate[] certs = (X509Certificate[]) request.getAttribute("java.security.cert.X509Certificate");
    X509Certificate cert = certs[0];

    The above works perfectly when ActivCard GOLD is used.

    Any help will be greatly appreciate it.

    KA

    DB:2.66:Actividentity Client V6.X And Jsp zj

    Our application is not working/responding when we use the ActivIdentity Client V6.x to process/interact with CAC Card (X509) Certification.
    The part of the JSP is failing inside the Jdeveloper is

    X509Certificate[] certs = (X509Certificate[]) request.getAttribute("java.security.cert.X509Certificate");
    X509Certificate cert = certs[0];

    The above works perfectly when ActivCard GOLD is used.

    Any help will be greatly appreciate it.

    KA

  • RELEVANCY SCORE 2.65

    DB:2.65:Rsa Encryption In Java p3


    Greetings
    C, i have a code:
    InputStream inStream = new FileInputStream("cert.cer");
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    X509Certificate cert = (X509Certificate)cf.generateCertificate(inStream);
    byte[] a = "Data to encrypt".getBytes();
    byte[] b = null;
    try {
    Cipher c = Cipher.getInstance("RSA/NONE/NoPadding");
    c.init(Cipher.ENCRYPT_MODE,cert); ///(***)
    b=c.doFinal(a);
    } catch (Exception e) {
    }
    //...

    Can anybody explain me,why on string signed (***) i recieve such exception:
    java.lang.NoSuchMethodError
    at javax.crypto.SunJCE_d.a(DashoA6275)
    at javax.crypto.SunJCE_d.a(DashoA6275)
    at javax.crypto.SunJCE_d.verify(DashoA6275)
    at javax.crypto.SunJCE_b.f(DashoA6275)
    at javax.crypto.SunJCE_b.clinit(DashoA6275)
    at javax.crypto.Cipher.getInstance(DashoA6275)
    at Demo.main(Demo.java:36)
    and how can i make it work?

    DB:2.65:Rsa Encryption In Java p3

    ok, i understand: now i m using another provider(www.bouncycastle.org), not SUN standart, cause of i need to encrypt data using SHA1withRSA algorithm. but so there more questions: how can i obtain Cipher object with a transformation SHA1withRSA?

  • RELEVANCY SCORE 2.65

    DB:2.65:Basecertloginmodule Fails To Pick Up Client Certificate 1z



    L.S.,I'm a relative newbie to JBoss. One of our applications exposes a web services interface. I'm trying to deploy the J2EE implementation of this application on JBoss. As part of this I'm trying to configure JBoss to require client certificates for the web service calls and to pass information from the certificate as the Principal to the application.I've done the following:- configure Tomcat for SSL. This works fine, regardless of the value of the clientAuth attribute.- define a (JAAS) securitydomain in conf/jboss-service.xml- define an application-policy in conf/login-config.xml, which contains the BaseCertLoginModule as the first login-module. This module refers to the securitydomain mentioned above- add a reference to the securitydomain in META-INF\jboss.xml in the jar that exposes the EJBs which make up the web service- define declarative security in the ejb-jar.xmlWhen I try to access the web service (I'm using a .NET client - not sure whether this might be relevant) I see the following in the JBoss logs (I've set logging of the security modules to the highest possible level):
    2007-08-01 11:12:20,705 TRACE [org.jboss.security.auth.spi.BaseCertLoginModule] initialize, instance=@20704708
    2007-08-01 11:12:20,705 TRACE [org.jboss.security.auth.spi.BaseCertLoginModule] securityDomain=java:/jaas/ITPForms-jboss
    2007-08-01 11:12:20,721 TRACE [org.jboss.security.auth.spi.BaseCertLoginModule] found domain: org.jboss.security.plugins.JaasSecurityDomain
    2007-08-01 11:12:20,721 TRACE [org.jboss.security.auth.spi.BaseCertLoginModule] exit: initialize(Subject, CallbackHandler, Map, Map)
    2007-08-01 11:12:20,721 TRACE [org.jboss.security.auth.spi.BaseCertLoginModule] enter: login()
    2007-08-01 11:12:20,721 TRACE [org.jboss.security.auth.spi.BaseCertLoginModule] login
    2007-08-01 11:12:20,721 TRACE [org.jboss.security.auth.spi.BaseCertLoginModule] enter: getAliasAndCert()
    2007-08-01 11:12:20,721 TRACE [org.jboss.security.auth.spi.BaseCertLoginModule] exit: getAliasAndCert()
    2007-08-01 11:12:20,721 TRACE [org.jboss.security.auth.spi.BaseCertLoginModule] Authenticating as unauthenticatedIdentity=null
    2007-08-01 11:12:20,721 TRACE [org.jboss.security.auth.spi.BaseCertLoginModule] enter: validateCredentail(String, X509Certificate)
    2007-08-01 11:12:20,721 WARN [org.jboss.security.auth.spi.BaseCertLoginModule] Domain, KeyStore, or cert is null. Unable to validate the certificate.
    2007-08-01 11:12:20,721 TRACE [org.jboss.security.auth.spi.BaseCertLoginModule] The supplied certificate DID NOT match the certificate in the keystore.
    2007-08-01 11:12:20,721 TRACE [org.jboss.security.auth.spi.BaseCertLoginModule] exit: validateCredentail(String, X509Certificate)
    2007-08-01 11:12:20,721 DEBUG [org.jboss.security.auth.spi.BaseCertLoginModule] Bad credential for alias=null

    DB:2.65:Basecertloginmodule Fails To Pick Up Client Certificate 1z


    You may get support if you ask in the web services forum. But I do not think it makes any difference because the ejb driven web services use the same security domain concept as the web archives.

  • RELEVANCY SCORE 2.64

    DB:2.64:Accessing Mscapi With Java 6 - Problem With Identical Aliases 1z


    Hi all,

    I'm trying to access MS Windows keystore from JAVA. It works with the new JAVA 6 SunMSCAPI support.

    But: I have three certificates in the MS store - all with the same 'alias'. The KeyStore.aliases() Enumeration gives me these three identical Strings, but afterwards I can not access a particular certificate as the only way to access them is by 'alias'....

    Of course I could get the first Certificate and delete it from the store, then the next etc.. until I have found the one I need. But this is bad, because afterwards the certificates are not any more in the MS store.

    Does any body know another possibility to access certificates in the keystore then accessing them by their alias ?

    this is some sample code illustrating the problem:

    KeyStore ks = KeyStore.getInstance("Windows-MY");
    ks.load(null, null);

    for(java.util.Enumeration e = ks.aliases(); e.hasMoreElements(); ) {
    String alias = (String)e.nextElement();
    System.out.print(alias);

    X509Certificate cert = (X509Certificate)ks.getCertificate(alias);
    System.out.println(" ,ID: "+cert.getSerialNumber().toString(16));
    }

    This gives (in my case) three identical Strings because I have three certificates in the store. When I access them and print out their serial nummer, I can see that always the same (the first) certificate is taken....

    Thanks very much for any ideas !

    DB:2.64:Accessing Mscapi With Java 6 - Problem With Identical Aliases 1z

    No ! your code is beatiful !!!!!

    Im trying to get this to work with a smartcard , connected to ms-capi.

    If it works with your reflection code I nominate you for Nobel price !! In fact i live only 500 meters from hall where the Nobel price banquet is held :-)

    if not I will have to look for another "provider" , with a better api.

    /Ludde

  • RELEVANCY SCORE 2.64

    DB:2.64:Sign Information With Reached Keystrore And Keystore.Privatekeyentry s9


    Hi, all
    I use Java 1.5 and I try to sign xml with real certificate and card reader, for this purpose I put in my %JAVA1.5_HOME%jre\lib\security new java.security file and replace the provider information with this:

    security.provider.7=sun.security.pkcs11.SunPKCS11 c:\\security\\pkcs11.cfg

    my pkcs11.cfg file has this information:
    name=Stampit
    library=c:\\WINDOWS\\system32\\pkcs201n.dll
    description=smart card

    and my source is

    KeyStore kst = KeyStore.getInstance("PKCS11");
    kst.load(null, pin);
    String alias = (String) kst.aliases().nextElement();
    Provider provider = kst.getProvider();

    /*KeyStore.CallbackHandlerProtection cpprotection = new
    KeyStore.CallbackHandlerProtection(new CallbackHandlerRoman());*/
    KeyStore.PasswordProtection pprotection = new KeyStore.PasswordProtection(pin);
    KeyStore.Builder builder = KeyStore.Builder.newInstance("PKCS11",
    provider,
    pprotection);
    KeyStore ks3 =builder.getKeyStore();

    KeyStore.PrivateKeyEntry pkEntry = (KeyStore.PrivateKeyEntry)ks3.getEntry(alias, pprotection);

    //Signature sign = Signature.getInstance("", provider);
    //sign.initVerify(cert);

    PrivateKey myPrivateKey = pkEntry.getPrivateKey();

    put when I print myPrivateKey is always:
    SunPKCS11-Stampit RSA private key, 1024 bits (id 10, token object, not sensitive, unextractable)

    when I sign with this source:
    File signatureFile = new File("d:/xml/signed.bulstata.xml");

    System.out.println(myPrivateKey);
    javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance();

    dbf.setNamespaceAware(true);
    javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder();
    org.w3c.dom.Document doc = db.parse(new File("D:/xml/bulstata.xml"));
    org.apache.xml.security.Init.init();
    String BaseURI = signatureFile.toURL().toString();
    XMLSignature sig = new XMLSignature(doc, BaseURI, XMLSignature.ALGO_ID_SIGNATURE_DSA);
    doc.getDocumentElement().appendChild(sig.getElement());

    Transforms transforms = new Transforms(doc);
    transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE);
    transforms.addTransform(Transforms.TRANSFORM_C14N_WITH_COMMENTS);
    sig.addDocument("", transforms, Constants.ALGO_ID_DIGEST_SHA1);

    X509Certificate cert = (X509Certificate) ks3.getCertificate("X509Cert");

    sig.addKeyInfo(cert);
    sig.addKeyInfo(cert.getPublicKey());
    sig.sign(myPrivateKey);

    always there si exception:
    Exception in thread "main" org.apache.xml.security.signature.XMLSignatureException: No installed provider supports this key: sun.security.pkcs11.P11Key$P11PrivateKey
    Original Exception was org.apache.xml.security.signature.XMLSignatureException: No installed provider supports this key: sun.security.pkcs11.P11Key$P11PrivateKey

    I try all various of this source with or without KeyStrore.Builder object. Why this exception is permanent and why the print of PrivateKey is with part "UNEXTRACTABLE", I this maybe I must try sun provider of Sun with IBM or I must try sign only with KeyStore.PrivateKeyEntry object. I can't find The cornerstore and I'm busy with this problem 2 days...Thank you for the help!

    DB:2.64:Sign Information With Reached Keystrore And Keystore.Privatekeyentry s9

    That is because you have asked for an XMLSignature object with the DSA algorithm (XMLSignature sig = new XMLSignature(doc, BaseURI, XMLSignature.ALGO_ID_SIGNATURE_DSA); and your key is an RSA key as indicated by your printout: SunPKCS11-Stampit RSA private key, 1024 bits (id 10, token object, not sensitive, unextractable). The two are incompatible.

    Either you need to generate a DSA key-pair on your card, or you need to create an XMLSignature object with the "SignatureMethod.RSA_SHA1" algorithm to perform the signing operation. Hope that helps.

  • RELEVANCY SCORE 2.64

    DB:2.64:The Request Was Aborted: Could Not Create Ssl/Tls Secure Channel. a8


    hi ;When I call java web service from .net applicationi face a problem  The request was aborted: Could not create SSL/TLS secure channel.howver i sent the certificte to the web service
     

    string certname = x;
     

    X509CertificateStore store = X509CertificateStore.LocalMachineStore(X509CertificateStore.MyStore);
    store.OpenRead();

     

    X509CertificateCollection col = (X509CertificateCollection)store.FindCertificateBySubjectString(certname);
     

    X509Certificate cert = null;
    cert = col[0];

    myservice.ClientCertificates.Add(cert);

    DB:2.64:The Request Was Aborted: Could Not Create Ssl/Tls Secure Channel. a8

    hi , i created a log file to trace the error with the ssl in the log System.Net Information: 0 : [6124] SecureChannel#10736886 - Left with 1 client certificates to choose from. System.Net Information: 0 : [6124] SecureChannel#10736886 - Trying to find a matching certificate in the certificate store. System.Net Information: 0 : [6124] SecureChannel#10736886 - Locating the private key for the certificate: [Subject]   CN=yessergsb, OU=IT, O=Arabian Advanced Systems Company, L=Riyadh, S=Riyadh, C=SA [Issuer]   CN=DigiCert Global CA, OU=www.digicert.com, O=DigiCert Inc, C=US [Serial Number]   0462034D279B47F49484CA553A054F47 [Not Before]   8/29/2009 3:00:00 AM [Not After]   9/3/2010 2:59:59 AM [Thumbprint]   0561B05052A1A155DF93D27AA360DE6FDEA224A0 . System.Net Information: 0 : [6124] SecureChannel#10736886 - Certificate is of type X509Certificate2 and contains the private key. System.Net Information: 0 : [6124] AcquireCredentialsHandle(package = Microsoft Unified Security Protocol Provider, intent  = Outbound, scc     = System.Net.SecureCredential) System.Net Information: 0 : [6124] InitializeSecurityContext(credential = System.Net.SafeFreeCredential_SECURITY, context = 5472fc8:54839f8, targetName = services-o.yesser.egov, inFlags = ReplayDetect, SequenceDetect, Confidentiality, AllocateMemory, InitManualCredValidation) System.Net Information: 0 : [6124] InitializeSecurityContext(In-Buffers count=2, Out-Buffer length=3066, returned code=ContinueNeeded). System.Net.Sockets Verbose: 0 : [6124] Socket#47943344::Send() System.Net.Sockets Verbose: 0 : [6124] Data from Socket#47943344::Send System.Net.Sockets Verbose: 0 : [6124] (printing 1024 out of 3066) System.Net.Sockets Verbose: 0 : [6124] 00000000 : 16 03 01 0B CA 0B 00 0A-BA 00 0A B7 00 06 27 30 : ..............'0 System.Net.Sockets Verbose: 0 : [6124] 00000010 : 82 06 23 30 82 05 0B A0-03 02 01 02 02 10 04 62 : ..#0...........b System.Net.Sockets Verbose: 0 : [6124] 00000020 : 03 4D 27 9B 47 F4 94 84-CA 55 3A 05 4F 47 30 0D : .M'.G....U:.OG0. System.Net.Sockets Verbose: 0 : [6124] 00000030 : 06 09 2A 86 48 86 F7 0D-01 01 05 05 00 30 5C 31 : ..*.H........0\1 System.Net.Sockets Verbose: 0 : [6124] 00000040 : 0B 30 09 06 03 55 04 06-13 02 55 53 31 15 30 13 : .0...U....US1.0. System.Net.Sockets Verbose: 0 : [6124] 00000050 : 06 03 55 04 0A 13 0C 44-69 67 69 43 65 72 74 20 : ..U....DigiCert System.Net.Sockets Verbose: 0 : [6124] 00000060 : 49 6E 63 31 19 30 17 06-03 55 04 0B 13 10 77 77 : Inc1.0...U....ww System.Net.Sockets Verbose: 0 : [6124] 00000070 : 77 2E 64 69 67 69 63 65-72 74 2E 63 6F 6D 31 1B : w.digicert.com1. System.Net.Sockets Verbose: 0 : [6124] 00000080 : 30 19 06 03 55 04 03 13-12 44 69 67 69 43 65 72 : 0...U....DigiCer System.Net.Sockets Verbose: 0 : [6124] 00000090 : 74 20 47 6C 6F 62 61 6C-20 43 41 30 1E 17 0D 30 : t Global CA0...0 System.Net.Sockets Verbose: 0 : [6124] 000000A0 : 39 30 38 32 39 30 30 30-30 30 30 5A 17 0D 31 30 : 90829000000Z..10 System.Net.Sockets Verbose: 0 : [6124] 000000B0 : 30 39 30 32 32 33 35 39-35 39 5A 30 7B 31 0B 30 : 0902235959Z0{1.0 System.Net.Sockets Verbose: 0 : [6124] 000000C0 : 09 06 03 55 04 06 13 02-53 41 31 0F 30 0D 06 03 : ...U....SA1.0... System.Net.Sockets Verbose: 0 : [6124] 000000D0 : 55 04 08 13 06 52 69 79-61 64 68 31 0F 30 0D 06 : U....Riyadh1.0.. System.Net.Sockets Verbose: 0 : [6124] 000000E0 : 03 55 04 07 13 06 52 69-79 61 64 68 31 29 30 27 : .U....Riyadh1)0' System.Net.Sockets Verbose: 0 : [6124] 000000F0 : 06 03 55 04 0A 13 20 41-72 61 62 69 61 6E 20 41 : ..U... Arabian A System.Net.Sockets Verbose: 0 : [6124] 00000100 : 64 76 61 6E 63 65 64 20-53 79 73 74 65 6D 73 20 : dvanced Systems System.Net.Sockets Verbose: 0 : [6124] 00000110 : 43 6F 6D 70 61 6E 79 31-0B 30 09 06 03 55 04 0B : Company1.0...U.. System.Net.Sockets Verbose: 0 : [6124] 00000120 : 13 02 49 54 31 12 30 10-06 03 55 04 03 13 09 79 : ..IT1.0...U....y System.Net.Sockets Verbose: 0 : [6124] 00000130 : 65 73 73 65 72 67 73 62-30 81 9F 30 0D 06 09 2A : essergsb0..0...* System.Net.Sockets Verbose: 0 : [6124] 00000140 : 86 48 86 F7 0D 01 01 01-05 00 03 81 8D 00 30 81 : .H............0. System.Net.Sockets Verbose: 0 : [6124] 00000150 : 89 02 81 81 00 A9 3E 17-F0 FF 7F 92 FA 1E A0 75 : ..............u System.Net.Sockets Verbose: 0 : [6124] 00000160 : BA F6 9E AB C4 5D EB 98-A6 DF 1B B1 8A 71 4B 64 : .....].......qKd System.Net.Sockets Verbose: 0 : [6124] 00000170 : 9B CF E8 12 06 CD 21 55-04 0D 46 B5 9E F6 23 66 : ......!U..F...#f System.Net.Sockets Verbose: 0 : [6124] 00000180 : F0 BC 63 57 7B 4E EF BE-91 F3 C0 4C E3 40 D2 B3 : ..cW{N.....L.@.. System.Net.Sockets Verbose: 0 : [6124] 00000190 : 8D 09 57 9A 69 DA AF 7F-9E 58 65 F9 08 5C 38 88 : ..W.i....Xe..\8. System.Net.Sockets Verbose: 0 : [6124] 000001A0 : 88 E3 A8 5B 95 1A E4 5C-31 D3 EB F3 95 2C 46 6F : ...[...\1....,Fo System.Net.Sockets Verbose: 0 : [6124] 000001B0 : 14 A2 30 0A DD D8 61 27-5C 02 D5 7D 29 47 4E 59 : ..0...a'\..})GNY System.Net.Sockets Verbose: 0 : [6124] 000001C0 : 99 7E 60 C1 41 A0 59 19-59 76 29 A3 35 63 A7 25 : .~`.A.Y.Yv).5c.% System.Net.Sockets Verbose: 0 : [6124] 000001D0 : F9 06 AA C4 F7 02 03 01-00 01 A3 82 03 44 30 82 : .............D0. System.Net.Sockets Verbose: 0 : [6124] 000001E0 : 03 40 30 1F 06 03 55 1D-23 04 18 30 16 80 14 A7 : .@0...U.#..0.... System.Net.Sockets Verbose: 0 : [6124] 000001F0 : C7 13 A0 7A 01 3C 9D EF-82 48 82 48 D5 73 51 B6 : ...z....H.H.sQ. System.Net.Sockets Verbose: 0 : [6124] 00000200 : 12 56 2A 30 1D 06 03 55-1D 0E 04 16 04 14 64 52 : .V*0...U......dR System.Net.Sockets Verbose: 0 : [6124] 00000210 : 7E 7E CB 7D AD 21 A9 44-70 07 68 EF 03 AB 53 A0 : ~~.}.!.Dp.h...S. System.Net.Sockets Verbose: 0 : [6124] 00000220 : 0D C8 30 76 06 08 2B 06-01 05 05 07 01 01 04 6A : ..0v..+........j System.Net.Sockets Verbose: 0 : [6124] 00000230 : 30 68 30 24 06 08 2B 06-01 05 05 07 30 01 86 18 : 0h0$..+.....0... System.Net.Sockets Verbose: 0 : [6124] 00000240 : 68 74 74 70 3A 2F 2F 6F-63 73 70 2E 64 69 67 69 : http://ocsp.digi System.Net.Sockets Verbose: 0 : [6124] 00000250 : 63 65 72 74 2E 63 6F 6D-30 40 06 08 2B 06 01 05 : cert.com0@..+... System.Net.Sockets Verbose: 0 : [6124] 00000260 : 05 07 30 02 86 34 68 74-74 70 3A 2F 2F 77 77 77 : ..0..4http://www System.Net.Sockets Verbose: 0 : [6124] 00000270 : 2E 64 69 67 69 63 65 72-74 2E 63 6F 6D 2F 43 41 : .digicert.com/CA System.Net.Sockets Verbose: 0 : [6124] 00000280 : 43 65 72 74 73 2F 44 69-67 69 43 65 72 74 47 6C : Certs/DigiCertGl System.Net.Sockets Verbose: 0 : [6124] 00000290 : 6F 62 61 6C 43 41 2E 63-72 74 30 0E 06 03 55 1D : obalCA.crt0...U. System.Net.Sockets Verbose: 0 : [6124] 000002A0 : 0F 01 01 FF 04 04 03 02-05 A0 30 0C 06 03 55 1D : ..........0...U. System.Net.Sockets Verbose: 0 : [6124] 000002B0 : 13 01 01 FF 04 02 30 00-30 7F 06 03 55 1D 1F 04 : ......0.0...U... System.Net.Sockets Verbose: 0 : [6124] 000002C0 : 78 30 76 30 39 A0 37 A0-35 86 33 68 74 74 70 3A : x0v09.7.5.3http: System.Net.Sockets Verbose: 0 : [6124] 000002D0 : 2F 2F 63 72 6C 33 2E 64-69 67 69 63 65 72 74 2E : //crl3.digicert. System.Net.Sockets Verbose: 0 : [6124] 000002E0 : 63 6F 6D 2F 44 69 67 69-43 65 72 74 47 6C 6F 62 : com/DigiCertGlob System.Net.Sockets Verbose: 0 : [6124] 000002F0 : 61 6C 43 41 2D 32 30 30-39 67 2E 63 72 6C 30 39 : alCA-2009g.crl09 System.Net.Sockets Verbose: 0 : [6124] 00000300 : A0 37 A0 35 86 33 68 74-74 70 3A 2F 2F 63 72 6C : .7.5.3http://crl System.Net.Sockets Verbose: 0 : [6124] 00000310 : 34 2E 64 69 67 69 63 65-72 74 2E 63 6F 6D 2F 44 : 4.digicert.com/D System.Net.Sockets Verbose: 0 : [6124] 00000320 : 69 67 69 43 65 72 74 47-6C 6F 62 61 6C 43 41 2D : igiCertGlobalCA- System.Net.Sockets Verbose: 0 : [6124] 00000330 : 32 30 30 39 67 2E 63 72-6C 30 82 01 C6 06 03 55 : 2009g.crl0.....U System.Net.Sockets Verbose: 0 : [6124] 00000340 : 1D 20 04 82 01 BD 30 82-01 B9 30 82 01 B5 06 0B : . ....0...0..... System.Net.Sockets Verbose: 0 : [6124] 00000350 : 60 86 48 01 86 FD 6C 01-03 00 01 30 82 01 A4 30 : `.H...l....0...0 System.Net.Sockets Verbose: 0 : [6124] 00000360 : 3A 06 08 2B 06 01 05 05-07 02 01 16 2E 68 74 74 : :..+.........htt System.Net.Sockets Verbose: 0 : [6124] 00000370 : 70 3A 2F 2F 77 77 77 2E-64 69 67 69 63 65 72 74 : p://www.digicert System.Net.Sockets Verbose: 0 : [6124] 00000380 : 2E 63 6F 6D 2F 73 73 6C-2D 63 70 73 2D 72 65 70 : .com/ssl-cps-rep System.Net.Sockets Verbose: 0 : [6124] 00000390 : 6F 73 69 74 6F 72 79 2E-68 74 6D 30 82 01 64 06 : ository.htm0..d. System.Net.Sockets Verbose: 0 : [6124] 000003A0 : 08 2B 06 01 05 05 07 02-02 30 82 01 56 1E 82 01 : .+.......0..V... System.Net.Sockets Verbose: 0 : [6124] 000003B0 : 52 00 41 00 6E 00 79 00-20 00 75 00 73 00 65 00 : R.A.n.y. .u.s.e. System.Net.Sockets Verbose: 0 : [6124] 000003C0 : 20 00 6F 00 66 00 20 00-74 00 68 00 69 00 73 00 :  .o.f. .t.h.i.s. System.Net.Sockets Verbose: 0 : [6124] 000003D0 : 20 00 43 00 65 00 72 00-74 00 69 00 66 00 69 00 :  .C.e.r.t.i.f.i. System.Net.Sockets Verbose: 0 : [6124] 000003E0 : 63 00 61 00 74 00 65 00-20 00 63 00 6F 00 6E 00 : c.a.t.e. .c.o.n. System.Net.Sockets Verbose: 0 : [6124] 000003F0 : 73 00 74 00 69 00 74 00-75 00 74 00 65 00 73 00 : s.t.i.t.u.t.e.s. System.Net.Sockets Verbose: 0 : [6124] Exiting Socket#47943344::Send()     - 3066#3066 System.Net.Sockets Verbose: 0 : [6124] Socket#47943344::Receive() System.Net.Sockets Verbose: 0 : [6124] Data from Socket#47943344::Receive System.Net.Sockets Verbose: 0 : [6124] 00000000 : 15 03 01 00 02                                  : ..... System.Net.Sockets Verbose: 0 : [6124] Exiting Socket#47943344::Receive()     - 5#5 System.Net.Sockets Verbose: 0 : [6124] Socket#47943344::Receive() System.Net.Sockets Verbose: 0 : [6124] Data from Socket#47943344::Receive System.Net.Sockets Verbose: 0 : [6124] 00000005 : 02 2A                                           : .* System.Net.Sockets Verbose: 0 : [6124] Exiting Socket#47943344::Receive()     - 2#2 System.Net Information: 0 : [6124] InitializeSecurityContext(credential = System.Net.SafeFreeCredential_SECURITY, context = 5472fc8:54839f8, targetName = services-o.yesser.egov, inFlags = ReplayDetect, SequenceDetect, Confidentiality, AllocateMemory, InitManualCredValidation) System.Net Information: 0 : [6124] InitializeSecurityContext(In-Buffers count=2, Out-Buffer length=0, returned code=CertUnknown). System.Net.Sockets Verbose: 0 : [6124] Socket#47943344::Dispose() System.Net Error: 0 : [6124] Exception in the HttpWebRequest#35213894:: - The request was aborted: Could not create SSL/TLS secure channel. System.Net Error: 0 : [6124] Exception in the HttpWebRequest#35213894::EndGetResponse - The request was aborted: Could not create SSL/TLS secure channel. but i can not guess what causing the error

  • RELEVANCY SCORE 2.64

    DB:2.64:Ssl Connection Security Error A Call To Sspi Failed The Message Was Badly Formatted.. Please Help!! d8


    Hi Guys,
    I have got wierd problem going on. I am trying to connect to Apple server via TCP/SSL. I am using a Client certificate provided by Apple for push notifications. I installed the certificate on my server (Win2k3) in both Local Trusted Root certificates and Local Personal Certificates folder.
    Now I have a class library that deals with that connection, when i call this class library from a console application running from the server it works absolutely fine, but when i call that class library from an asp.net page or asmx web service I get the following exception.
    A call to SSPI failed, see inner exception. The message received was unexpected or badly formatted.
    This is my code:
    X509Certificate cert = new X509Certificate(certificateLocation, certificatePassword); X509CertificateCollection certCollection = new X509CertificateCollection(new X509Certificate[1] { cert }); // OPEN the new SSL Stream SslStream ssl = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null); ssl.AuthenticateAsClient(ipAddress, certCollection, SslProtocols.Default, false);
    ssl.AuthenticateAsClient is where the error gets thrown.
    This is driving me nuts.. If the console application can connect fine, there must be some problem with asp.net network layer security that is failing the authentication... not sure, perhaps need to add something or some sort of security policy in the web.config. Also just to point out that i can connect fine on my local development machine both with console and website.
    Any one has got any ideas.. Any help appreciated..

    DB:2.64:Ssl Connection Security Error A Call To Sspi Failed The Message Was Badly Formatted.. Please Help!! d8

    Thanks Feroze, that was it.. If any one else gets the same problem this is what you have to do.. Since Aspnet runs under a different account so you have to use WinHttpCertCfg.exe tool to allow the following account to access the certificate which you should install in Local Computer Personal/Trusted folders.. ASPNET Network Service Authenticated Users e.g. winhttpcertcfg -g -c LOCAL_MACHINE\MY -s CertificateName -a ASPNET where certificate name is the friendly name of your certificate. You can get the tool and information from the link below: http://msdn.microsoft.com/en-us/library/aa384088%28VS.85%29.aspx#_using Regards
    Noman M.
    If a post answers your question or is helpful then please mark it as an answer or Vote as helpful.

  • RELEVANCY SCORE 2.64

    DB:2.64:Performance Monitor Error At Getservercertificate km


    Hello,

    I am posting again (I hope this time it's more readable).

    I just downloaded and installed last version of BEA Performance Monitor for WLS 8.1. My WebLogic is in a development environment, with no license. At console startup, I get the following error:
    br
    bException encountered while processing content in console extension:
    javax.servlet.ServletException: weblogic.security.service.SSLManager.getServerCertificate(Lweblogic/security/u
    tils/SSLContextWrapper;)[Ljavax/security/cert/X509Certificate;
    at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:469)
    at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:463)
    at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:315)
    at weblogic.servlet.internal.RequestDispatcherImpl.include(RequestDispatcherImpl.java:638)
    at weblogic.servlet.internal.RequestDispatcherImpl.include(RequestDispatcherImpl.java:423)
    at weblogic.management.console.tags.IncludeTag.doDispatcherInclude(IncludeTag.java:121)
    at weblogic.management.console.tags.IncludeTag.doStartTag(IncludeTag.java:83)
    at weblogic.management.console.tags.ExtensibleTagDelegate.doExtensions(ExtensibleTagDelegate.java:192)

    at weblogic.management.console.tags.ExtensibleTagDelegate.doExtensionContent(ExtensibleTagDelegate.jav
    a:171)
    at weblogic.management.console.tags.nav.NavNodeTag.doEndTag(NavNodeTag.java:141)
    at weblogic.management.console.webapp._domain.__nav._jspService(__nav.java:2060)
    at weblogic.servlet.jsp.JspBase.service(JspBase.java:33)
    at weblogic.servlet.internal.ServletStubImpl$ServletInvocationAction.run(ServletStubImpl.java:1006)
    at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:419)
    at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:315)
    at weblogic.servlet.internal.RequestDispatcherImpl.forward(RequestDispatcherImpl.java:322)
    at weblogic.servlet.jsp.PageContextImpl.forward(PageContextImpl.java:150)
    at weblogic.management.console.actions.ForwardAction.perform(ForwardAction.java:35)
    at weblogic.management.console.actions.internal.ActionServlet.doAction(ActionServlet.java:173)
    at weblogic.management.console.actions.internal.ActionServlet.doGet(ActionServlet.java:91)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:740)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
    at weblogic.servlet.internal.ServletStubImpl$ServletInvocationAction.run(ServletStubImpl.java:1006)
    at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:419)
    at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:315)
    at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.jav
    a:6718)
    at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
    at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:121)
    at weblogic.servlet.internal.WebAppServletContext.invokeServlet(WebAppServletContext.java:3764)
    at weblogic.servlet.internal.ServletRequestImpl.execute(ServletRequestImpl.java:2644)
    at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:219)
    at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:178)
    --------------- nested within: ------------------
    weblogic.management.console.utils.NestedJspException: weblogic.security.service.SSLManager.getServerCertificat
    e(Lweblogic/security/utils/SSLContextWrapper;)[Ljavax/security/cert/X509Certificate; - with nested exception:
    [javax.servlet.ServletException: weblogic.security.service.SSLManager.getServerCertificate(Lweblogic/security/
    utils/SSLContextWrapper;)[Ljavax/security/cert/X509Certificate;]
    at weblogic.management.console.tags.IncludeTag.doStartTag(IncludeTag.java:86)
    at weblogic.management.console.tags.ExtensibleTagDelegate.doExtensions(ExtensibleTagDelegate.java:192)

    at weblogic.management.console.tags.ExtensibleTagDelegate.doExtensionContent(ExtensibleTagDelegate.jav
    a:171)
    at weblogic.management.console.tags.nav.NavNodeTag.doEndTag(NavNodeTag.java:141)
    at weblogic.management.console.webapp._domain.__nav._jspService(__nav.java:2060)
    at weblogic.servlet.jsp.JspBase.service(JspBase.java:33)
    at weblogic.servlet.internal.ServletStubImpl$ServletInvocationAction.run(ServletStubImpl.java:1006)
    at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:419)
    at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:315)
    at weblogic.servlet.internal.RequestDispatcherImpl.forward(RequestDispatcherImpl.java:322)
    at weblogic.servlet.jsp.PageContextImpl.forward(PageContextImpl.java:150)
    at weblogic.management.console.actions.ForwardAction.perform(ForwardAction.java:35)
    at weblogic.management.console.actions.internal.ActionServlet.doAction(ActionServlet.java:173)
    at weblogic.management.console.actions.internal.ActionServlet.doGet(ActionServlet.java:91)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:740)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
    at weblogic.servlet.internal.ServletStubImpl$ServletInvocationAction.run(ServletStubImpl.java:1006)
    at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:419)
    at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:315)
    at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.jav
    a:6718)
    at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
    at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:121)
    at weblogic.servlet.internal.WebAppServletContext.invokeServlet(WebAppServletContext.java:3764)
    at weblogic.servlet.internal.ServletRequestImpl.execute(ServletRequestImpl.java:2644)
    at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:219)
    at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:178)/b
    br
    At administrative server startup, the following information (for reference) appears:
    br
    b04/06/2005 22:11:04 CEST Info WebLogicServer BEA-000377 Starting WebLogic Server with Java HotSpot(TM
    ) Client VM Version 1.4.2_05-b04 from Sun Microsystems Inc.
    04/06/2005 22:11:04 CEST Info Configuration Management BEA-150016 This server is being started as the
    administration server.
    04/06/2005 22:11:04 CEST Info Management BEA-141107 Version: WebLogic Server 8.1 SP4 Mon Nov 29 16:2
    1:29 PST 2004 471647
    WebLogic XMLX Module 8.1 SP4 Mon Nov 29 16:21:29 PST 2004 471647
    04/06/2005 22:11:04 CEST Notice Management BEA-140005 Loading domain configuration from configuration
    repository at E:\dat\workplace\weblogic\mydomain\.\config.xml.
    04/06/2005 22:11:06 CEST Notice Log Management BEA-170019 The server log file E:\dat\workplace\weblog
    ic\mydomain\myserver\myserver.log is opened. All server side log events will be written to this file.
    04/06/2005 22:11:07 CEST Notice Security BEA-090082 Security initializing using security realm myreal
    m.
    04/06/2005 22:11:07 CEST Notice WebLogicServer BEA-000327 Starting WebLogic Admin Server "myserver" f
    or domain "mydomain"
    ClassLoaderIPre-processor com.dirig.preprocessor.DirigBEAClassProcessor loaded and initialized
    04/06/2005 22:11:11 CEST Notice WebLogicServer BEA-000331 Started WebLogic Admin Server "myserver" fo
    r domain "mydomain" running in Development Mode
    04/06/2005 22:11:11 CEST Notice WebLogicServer BEA-000360 Server started in RUNNING mode
    04/06/2005 22:11:11 CEST Notice WebLogicServer BEA-000355 Thread "ListenThread.Default" listening on
    port 7001, ip address *.*
    04/06/2005 22:11:32 CEST Notice Security BEA-090170 Loading the private key stored under the alias De
    moIdentity from the jks keystore file E:\bin\computing\software\engineering\server\application\WebLogic\bin\se
    rver\lib\DemoIdentity.jks.

    Could anybody tell me what I am doing wrong? I rechecked several times the documentaion and can't see any step i didn't follow during installation./b
    br
    Thank you in advance.
    br
    Dimas

    DB:2.64:Performance Monitor Error At Getservercertificate km

    As this happens only when the console is opened. Is it just a problem with "core weblogic code" or a problem with the demo ceritificate its trying to use .. BTW the PMCE doc said that it uses two-way ssl .. So i tried all possible combinations .. enabled two-way ssl .. disabled ssl .. turned on SSL DEBUG trace ..etc .. doesnt look lik e certificate problem ..

    This is so pathetic that BEA has a FREE DECENT PERF TOOL which is so buggy that cannot be used ..

    Please keep us posted ..

  • RELEVANCY SCORE 2.63

    DB:2.63:Initializing Cipher With Certificate Instead Of Secretkey? 79


    Hi there folks!

    Been struggling a while with this one. I need to initialize my Cipher with a certificate instead of a SecretKey object. I use JCE 1.2.2 and JDK1.3.1. I created my X.509 certificate with the keytool, selecting default values for it, and then exported it to a .CER file. I can read the certificate in, but when I try to initialize the Cipher, it throws the following exception:

    java.security.InvalidKeyException: Wrong algorithm: DES required
    at com.sun.crypto.provider.SunJCE_ad.a(DashoA6275)
    at com.sun.crypto.provider.SunJCE_ab.a(DashoA6275)
    at com.sun.crypto.provider.DESCipher.engineInit(DashoA6275)
    at javax.crypto.Cipher.init(DashoA6275)
    at javax.crypto.Cipher.init(DashoA6275)
    at coza.arivia.encryption.EncryptWithX509.main(EncryptWithX509.java:40)

    I surmise that the error lies in my choice of transformation, namely "DES", at the line:
    Cipher desCipher = Cipher.getInstance("DES");

    But if not DES, then what else should I use?!

    Many thanks for ANY help forthcoming! Here's the code:

    public static void main(String args[]) {
    try {
    java.security.Security.addProvider(new com.sun.crypto.provider.SunJCE());

    //My X.509 certificate
    InputStream inStream = new FileInputStream("C:/DevRoot/EncryptionTest/mycert_DER_Encoded.cer");
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    X509Certificate cert = (X509Certificate)cf.generateCertificate(inStream);
    inStream.close();

    // Initialize the cipher for encryption
    Cipher desCipher = Cipher.getInstance("DES");
    desCipher.init(Cipher.ENCRYPT_MODE, cert);

    // The cleartext
    byte[] cleartext = "Forgo the Inevitable Cornflakes!".getBytes();

    // Encrypt the cleartext
    byte[] ciphertext = desCipher.doFinal(cleartext);

    // Initialize the same cipher for decryption
    desCipher.init(Cipher.DECRYPT_MODE, cert);

    // Decrypt the ciphertext
    byte[] decryptedText = desCipher.doFinal(ciphertext);

    System.out.println("Clear text = " + new String(cleartext));
    System.out.println("Cipher text = " + new String(ciphertext));
    System.out.println("Decrypted text = " + new String(decryptedText));
    }
    catch (java.security.cert.CertificateException e) {
    e.printStackTrace();
    }
    catch (java.security.NoSuchAlgorithmException e) {
    e.printStackTrace();
    }
    catch (java.security.InvalidKeyException e) {
    e.printStackTrace();
    }
    catch (javax.crypto.IllegalBlockSizeException e) {
    e.printStackTrace();
    }
    catch (javax.crypto.NoSuchPaddingException e) {
    e.printStackTrace();
    }
    catch (javax.crypto.BadPaddingException e) {
    e.printStackTrace();
    }
    catch (IOException e) {
    e.printStackTrace();
    }
    }

    DB:2.63:Initializing Cipher With Certificate Instead Of Secretkey? 79

    You are right that privateKey encryption of data can be used to verify authenticity of the sender it is insecure. You should instead use Signatures which in essence is private key encryption but it applies padding and salt to reduce the plaintext attacks on the private key.

    Something like RSAWithSHA1_PKCS1v1.5 or even better the new standard RSASSA-PSS.

    Both of these signatures is in essance RSA encryption with a private key. However, it is not the message itself that is encrypted but rather a message digest of the message. Plus both of the above signature schemes use some pretty fancy padding/randomization of message to limit the effectivness of plaintext attacks on the private key.

  • RELEVANCY SCORE 2.63

    DB:2.63:Certficate Import p3


    Hi
    I importing a Ca certificate via java code
    and I can't connect to the trusted server .
    only when i restart my program i can connect to the server via https :\\

    how can i makethe crtificate work in my current run
    the code:
    String path = System.getProperty("java.home")+"\\lib\\security\\cacerts";
    java.io.FileInputStream cacerts= new java.io.FileInputStream(path);
    ByteArrayInputStream stream = new ByteArrayInputStream(buff);
    KeyStore store= KeyStore.getInstance(KeyStore.getDefaultType());
    char [] password ={'c','h','a','n','g','e','i','t'};
    store.load(cacerts,password);
    CertificateFactory certFactory=CertificateFactory.getInstance("X.509");
    X509Certificate cert= (X509Certificate)certFactory.generateCertificate(stream);
    System.out.println(cert);
    store.deleteEntry(serverId);
    store.setCertificateEntry(serverId,cert);
    System.out.println(cert.toString());
    java.io.FileOutputStream s = new java.io.FileOutputStream(path);
    store.store(s,password);
    s.close();
    cacerts= new java.io.FileInputStream(path);

    DB:2.63:Certficate Import p3

    I don't think its possible to import a key programmatically, or at least I wasn't able to do it. In order to get a certificate loaded up a runtime I use System.exec to execute keytool. If someone knows better, please speak up!

  • RELEVANCY SCORE 2.63

    DB:2.63:Security Cert. Issue pm



    I cannot log in I get:

    There is a problem with this website's security certificate.

    DB:2.63:Security Cert. Issue pm


    I cannot log in I get:

    There is a problem with this website's security certificate.

  • RELEVANCY SCORE 2.63

    DB:2.63:Replacing X509certificate In Jsse And Jdk 1.4 k1


    Can anyone help me figure out how to replace the X509Certificate implementation in JSSE with JDK 1.4?

    The docs state to set the security property cert.provider.x509v1, which I have tried both dynamically (through Security.setProperty()) and statically (via the java.security file).

    Neither of these methods seem to work.

    I have place breakpoints (and instrumentation) in my X509Certificate implementation, but my code is not invoked. I have also set javax.net.debug=all to see if I could gather any clues, but I don't see anything in the debug output related to specification of the X509Certificate class.

    Has anyone had any success with this?

    DB:2.63:Replacing X509certificate In Jsse And Jdk 1.4 k1

    OK, I found a work-around.

    At the beginning of my program I do the following:

    try { c = Cipher.getInstance("RC4"); }
    catch (Exception e) { }
    Security.insertProviderAt(new my.pkg.Provider(),1);

    The idea is to use the standard provider setup during a throw-away call to Cipher.getInstance(). The sole purpose of invoking Cipher.getInstance() is to force the classloader to check the signature on rt.jar and jsse.jar.
    Once this is done, it's safe to replace the default CertificateFactory for X509 certificates. So after the jar sigs have been forcefully checked, I then add my provider in the preferred priority slot (#1).

    Then JSSE will use my X509Certificate implementation, which passes!

    Good night!
    Terence

  • RELEVANCY SCORE 2.62

    DB:2.62:Query Multivalue Ldap Attribute dp


    Hi:

    I'm using AD as LDAP server and I need to query one attibute: userCertificate

    So I have a user that has several certificates stored and so it has several instances of the attribute userCertificate:

    userCertificate = 1
    userCertificate = 2

    Well I'm a newbie, and I only can retrive the first instance of the attribute. I don't know how to retrieve the remaning ones....

    Any ideas?

    LinkedList list = new LinkedList();
    NamingEnumeration results = null;

    try {
    SearchControls controls = new SearchControls();
    controls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    results = ctx.search( baseDN, filter, controls);

    while (results.hasMore()) {
    SearchResult searchResult = (SearchResult) results.next();
    Attributes attributes = searchResult.getAttributes();
    Attribute attr = attributes.get("userCertificate");

    try {
    X509Certificate cert = null;

    try {
    ByteArrayInputStream bais = new ByteArrayInputStream( (byte[])attr.get() );
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    Collection c = cf.generateCertificates (bais);
    Iterator i = c.iterator ();
    //cert = (X509Certificate)cf.generateCertificate(bais);
    while (i.hasNext ())
    {
    cert = (X509Certificate) i.next ();
    System.out.println(cert);
    list.add(cert);
    }

    } catch (Exception e) {
    System.err.println(e);

    }

    //list.add(cn);
    } catch (Exception e) {
    System.out.println(e.toString());
    //System.out.println(e.printStackTrace());
    }
    }
    ....

    Message was edited by:
    Thx1011_2

    DB:2.62:Query Multivalue Ldap Attribute dp

    Hi!

    Thank you very much.

    It works. Now I can retrieve all user certificates from the AD attribute.

    Regarding the newbie, well my problem is not Java basic constructs as a language, but how to use the available API to do the required job...

    Most documentation explains the API but doesn't show any examples, and how it can be used....

    Most books explain the While, the For, etc... but not how interface with real systems with the API...

    Thanks for your help!

  • RELEVANCY SCORE 2.62

    DB:2.62:Implementing Checkclienttrusted(X509cert) Of X509trustmanager a8


    Hi,

    I'm operating on Weblogic classes I have something that acts as checkClientTrusted - weblogic TrustManager.certificateCalback when u get the peer cert chain.

    So I am in a position where I have my custom keystore (ie jre cacerts) and the peer certificate chain and the certificateCallback should return true if peer is trusted. I don't have java automatic mechanizm that is used in i.e X509TrustManagerImpl.checkclienttrusted.
    How is the simplest but reliable way to return true if peer is trusted...

    Do u thing something like someMyKeystorecert.equals(somePeerCert) would be convienient?
    aliases = this.keyStore.aliases();
    ListX509Certificate x509CertsList = new ArrayListX509Certificate();
    while (aliases.hasMoreElements()) {
    String alias = (String) aliases.nextElement();
    Certificate[] certs = keyStore.getCertificateChain(alias);

    for (int c = 0 ; c certs.length ; c++) {
    if ( certs[c] instanceof X509Certificate ) {
    X509Certificate cert = (X509Certificate) certs[c];
    x509CertsList.add(cert);
    }
    }
    }
    X509Certificate[] x509CertsArray = (X509Certificate[]) x509CertsList
    .toArray(new X509Certificate[x509CertsList.size()]);

    X509Certificate cer = x509CertsArray[0];
    //sample comparison of one of them
    //TODO check all of them
    if (cer.equals(arg0[0])){
    return true;
    }By the way - the following trustedSet doesnt have my self signed cert that I added to cacerts. why?
    SetX509Certificate trustedSet=KeyStores.getTrustedCerts(keyStore);

    IteratorX509Certificate it = trustedSet.iterator();
    while (it.hasNext()){
    X509Certificate cert = it.next();
    System.out.println(" certificate " + cert.toString());

    }

    DB:2.62:Implementing Checkclienttrusted(X509cert) Of X509trustmanager a8

    Hi,

    I'm operating on Weblogic classes I have something that acts as checkClientTrusted - weblogic TrustManager.certificateCalback when u get the peer cert chain.

    So I am in a position where I have my custom keystore (ie jre cacerts) and the peer certificate chain and the certificateCallback should return true if peer is trusted. I don't have java automatic mechanizm that is used in i.e X509TrustManagerImpl.checkclienttrusted.
    How is the simplest but reliable way to return true if peer is trusted...

    Do u thing something like someMyKeystorecert.equals(somePeerCert) would be convienient?
    aliases = this.keyStore.aliases();
    ListX509Certificate x509CertsList = new ArrayListX509Certificate();
    while (aliases.hasMoreElements()) {
    String alias = (String) aliases.nextElement();
    Certificate[] certs = keyStore.getCertificateChain(alias);

    for (int c = 0 ; c certs.length ; c++) {
    if ( certs[c] instanceof X509Certificate ) {
    X509Certificate cert = (X509Certificate) certs[c];
    x509CertsList.add(cert);
    }
    }
    }
    X509Certificate[] x509CertsArray = (X509Certificate[]) x509CertsList
    .toArray(new X509Certificate[x509CertsList.size()]);

    X509Certificate cer = x509CertsArray[0];
    //sample comparison of one of them
    //TODO check all of them
    if (cer.equals(arg0[0])){
    return true;
    }By the way - the following trustedSet doesnt have my self signed cert that I added to cacerts. why?
    SetX509Certificate trustedSet=KeyStores.getTrustedCerts(keyStore);

    IteratorX509Certificate it = trustedSet.iterator();
    while (it.hasNext()){
    X509Certificate cert = it.next();
    System.out.println(" certificate " + cert.toString());

    }

  • RELEVANCY SCORE 2.62

    DB:2.62:Post Xml Data Over Https Url Using Webhttprequest. 8a


    Hi,

    I am using HttpWebRequest to post XML data to SSL URL.

    I am using .NET 4.0 and tried many things but nothing worked for me.

    1. I have tried adding Cert using in request but it also fails.
    X509Certificate Cert
    try
    {

    ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(ValidateServerCertificate);

    ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;

    X509Certificate Cert = null

    #region Certificates
    string issuerName = My CA;

    X509Store store = new X509Store(StoreName.Root);
    store.Open(OpenFlags.MaxAllowed);
    X509CertificateCollection col =
    (X509CertificateCollection)store.Certificates.Find(X509FindType.FindByIssuerName, issuerName, true);

    Cert = col[0];

    #endregion

    string RequestString = clsReq.GetModifiedXML();

    string URL = @https://url/abc;
    HttpWebRequest salesRequest = (HttpWebRequest)WebRequest.Create(URL);

    // Adding Certificate in request....
    salesRequest.ClientCertificates.Add(Cert);
    salesRequest.KeepAlive = false;


    salesRequest.Credentials = CredentialCache.DefaultCredentials;

    salesRequest.Method = POST;
    //salesRequest.ContentType = application/x-www-form-urlencoded;
    // salesRequest.ContentType = text/html;
    salesRequest.ContentType = text/xml;

    StreamWriter postdatastream = new StreamWriter(salesRequest.GetRequestStream());

    postdatastream.WriteLine(RequestString);
    postdatastream.Close();

    HttpWebResponse salesResponse = (HttpWebResponse)salesRequest.GetResponse();

    if (salesResponse.StatusCode == HttpStatusCode.OK)
    {
    StreamReader streader = new StreamReader(salesResponse.GetResponseStream());
    string result = streader.ReadToEnd();
    streader.Close();

    Response.Write(result);

    }

    salesResponse.Close();

    }
    catch (Exception ex)
    {

    }

    Please help.

    Sandy..

    DB:2.62:Post Xml Data Over Https Url Using Webhttprequest. 8a

    Hi All,
    The code which I used was good. Actually certificate looks was not properly configured. We have set password with certificate and add the password in code while using certificate and it works,

    thanks all for your answers.
    Sandy..

  • RELEVANCY SCORE 2.61

    DB:2.61:Trsutmanager With Java 1.4 zj


    In my https server i want to accept all clients with trusted and not trusted certificates.

    So i defined my X509TrustManager:
    public class MYX509TrustManager implements X509TrustManager {
    X509TrustManager sunX509TrustManager;
    Logger log = Logger.getLogger("X509TrustManager");
    MYX509TrustManager() {
    sunX509TrustManager = (X509TrustManager) tmf.getTrustManagers()[0];
    }

    public void checkClientTrusted(X509Certificate chain[], String authType) throws CertificateException {
    log.debug("---checkClientTrusted");
    //sunX509TrustManager.checkClientTrusted(chain,authType);
    }

    public void checkServerTrusted(X509Certificate chain[],String authType) throws CertificateException{
    log.debug("checkServerTrusted");
    sunX509TrustManager.checkServerTrusted(chain,authType);
    };

    public X509Certificate[] getAcceptedIssuers() {
    log.debug("---getAcceptedIssuers");
    return sunX509TrustManager.getAcceptedIssuers();
    }

    }

    When a client with a trusted certificate call the server,
    i see in the log
    ---getAcceptedIssuers
    ---checkClientTrusted..

    But when the client with a "not trusted certificate" call the server,
    i see in the log only the line
    ---getAcceptedIssuers

    Why the method checkClientTrusted isn't called ?

    i have an javax.net.ssl.SSLHandshakeException: null cert chain ?
    I have seen in the jsse reference guide and i seem
    that my X509Trumanager definition it's correct.
    Anybody can help me ?

    DB:2.61:Trsutmanager With Java 1.4 zj

    Hi,

    I've the similar problem under 1.4.2. Did someone solve the problem?

    Simon

  • RELEVANCY SCORE 2.61

    DB:2.61:Signature Verficiation Fails sx


    Hi everybody,

    I have an issue that my XML signature cannot be verified with an external (e-government) tool. The XML document contains an xml-stylesheet directive and this causes a problem. if I remove it, an XML is signed and verified correctly as well. The signature can be, however, verified with a simple Java application I wrote (I don't know what's difference between those two tools - but normally it must be verifiable with any tool - right?). Can someone help me pls? Thanks in advance.

    Here is my code:

    -----
    org.apache.xml.security.Init.init();
    ElementProxy.setDefaultPrefix(Constants.SignatureSpecNS, "ds");

    XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");
    Document signedDocument = signRequest.getDocument();

    Reference ref = fac.newReference("", fac.newDigestMethod(
    DigestMethod.SHA1, null), Collections.singletonList(fac
    .newTransform(Transform.ENVELOPED,
    (TransformParameterSpec) null)), null, null);

    SignedInfo si = fac
    .newSignedInfo(fac.newCanonicalizationMethod(
    CanonicalizationMethod.INCLUSIVE,
    (C14NMethodParameterSpec) null), fac
    .newSignatureMethod(SignatureMethod.RSA_SHA1, null),
    Collections.singletonList(ref));

    X509Certificate cert = (X509Certificate) signRequest.getCertificate();

    KeyInfoFactory kif = fac.getKeyInfoFactory();
    List x509Content = new ArrayList();
    x509Content.add(cert.getSubjectX500Principal().getName());
    x509Content.add(cert);
    X509Data xd = kif.newX509Data(x509Content);
    KeyInfo ki = kif.newKeyInfo(Collections.singletonList(xd));

    DOMSignContext dsc = new DOMSignContext(signRequest.getPrivateKey(),
    signedDocument.getDocumentElement());

    XMLSignature signature = fac.newXMLSignature(si, ki);

    signature.sign(dsc);
    -----

    I found this code on Oracle Java. Before it I tried to use the Apache Santuario but I used XmlSiganture object directly (no Factory is used) - the same effect.

    I tried to use Reference in order to sign only root element but the only way I know is to use element id - #my_id to access an element. And this doesn't work as well :-(.

    Thanks for any help.

    Regard,
    erno

    Edited by: user5845341 on 21.02.2012 08:02

    DB:2.61:Signature Verficiation Fails sx

    Maybe one detail more: signing the same document with and without xslt-stylesheet directive gives me different digest values and signature values as well. If I say that my root node should be signed how is it possible that those changes are relevant? Is whole document always signed? I really don't get it... Any tips? Thnx for any help.

    regards

  • RELEVANCY SCORE 2.61

    DB:2.61:Validate Certificates From Received Xml Document jf


    Hi,

    I'm new to the Cryto API and have read the Java Cert Path API Prog. Guide. But I'm still not crystal clear on some details.

    (1) In the code below, at (a), which certificate should I put in the selector? Note that the document may contain a chain of X509Certificates, but PKIBuilderParam seems to take only one cert via X509CertSelector

    (2) Is CertPath validation still needed? (At point (b).) I think it is not needed as we build the CP already, but then I'm not sure.

    (3) The code runs successfully but the "cp" list is empty. Is that normal? Note: the truststore key store contains the certificate found in the document.

    (4) Do I miss anything else?

    Thanks a lot!

    Here is what my code looks like:

    // The XML has certs in the XML signature. (We collect them using
    // Apache XML Security library)
    ArrayListX509Certificate certList = obj.getX509Certificates();

    X509CertSelector selector = new X509CertSelector();
    selector.setCertificate(certList.get(0)); // (a)
    PKIXParameters params =
    new PKIXBuilderParameters(trustStore, selector);
    CertPathBuilder cpb = CertPathBuilder.getInstance("PKIX");
    CertPath cp = cpb.build(params).getCertPath();
    List certs = cp.getCertificates();
    Iterator i = certs.iterator();
    while (i.hasNext()) {
    X509Certificate c = (X509Certificate) i.next();
    System.out.println(c);
    }

    // (b)
    CertPathValidator cpv = CertPathValidator.getInstance("PKIX");
    CertPathValidatorResult cpvResult = cpv.validate(cp, params);

    DB:2.61:Validate Certificates From Received Xml Document jf

    Thanks a lot!

    The certificate is indeed in the trust store already. So I'm almost there except that I need to find the last signer's certificate among the certificates found in the document.

    While I can probably just compare the certificate's subject DN and verify each one until I found the root, is there a tool in java.security or in some other 3rd party library to do this?

    Thanks again!

  • RELEVANCY SCORE 2.60

    DB:2.60:Classcastexception In Certificateloginmodule ap



    While implementing JAAS security into my JBossESB i stumbled on a ClassCastException in the CertificateLoginModule. While debugging i found the code where the problem occurs:

    private X509Certificate getCallerCertificate(final ObjectCallback objectCallback) throws LoginException
    {
    final Set? credentials = (Set?) objectCallback.getCredential();
    if (credentials == null || credentials.isEmpty())
    {
    throw new LoginException("No X509Certificate was passed to the login module");
    }

    X509Certificate callerCert = null;
    for (Object object : credentials)
    {
    if (object instanceof X509Certificate)
    {
    callerCert = (X509Certificate) object;
    break;
    }
    }

    if (callerCert == null)
    {
    throw new LoginException("No X509Certificate was passed to the login module");
    }

    return callerCert;
    }

    DB:2.60:Classcastexception In Certificateloginmodule ap


    Hi Hans,

    sorry, but I'm can't really give you an answer to when this will be implemented as it is not for me to decide. You can vote for this issue though and that will be taken into consideration when tasks get prioritized.

    Regards,

    /Daniel

  • RELEVANCY SCORE 2.60

    DB:2.60:Bouncycastle Pkcs#7 Encryption Problem cx


    I want to use BouncyCastle to encrypt and decrypt with pkcs7 format. I have a hardware token. when I use Keypair in jks file in my hard drive it work fine but when i use key pair in token its not work. this is my exception:
    Exception in thread "main" org.bouncycastle.cms.CMSException: cannot create cipher: No such algorithm: 2.16.840.1.101.3.4.1.2
    at org.bouncycastle.cms.jcajce.EnvelopedDataHelper.createCipher(Unknown Source)
    at org.bouncycastle.cms.jcajce.EnvelopedDataHelper$1.doInJCE(Unknown Source)
    at org.bouncycastle.cms.jcajce.EnvelopedDataHelper.execute(Unknown Source)
    at org.bouncycastle.cms.jcajce.EnvelopedDataHelper.createContentCipher(Unknown Source)
    at org.bouncycastle.cms.jcajce.JceKeyTransEnvelopedRecipient.getRecipientOperator(Unknown Source)
    at org.bouncycastle.cms.KeyTransRecipientInformation.getRecipientOperator(Unknown Source)
    at org.bouncycastle.cms.RecipientInformation.getContentStream(Unknown Source)
    at org.bouncycastle.cms.RecipientInformation.getContent(Unknown Source)
    at pktb.PKTB.CmsDecrypt(PKTB.java:288)
    at pktb.PKTB.main(PKTB.java:419)
    Caused by: java.security.NoSuchAlgorithmException: No such algorithm: 2.16.840.1.101.3.4.1.2
    at javax.crypto.Cipher.getInstance(DashoA13*..)
    at javax.crypto.Cipher.getInstance(DashoA13*..)
    at org.bouncycastle.jcajce.NamedJcaJceHelper.createCipher(Unknown Source)
    ... 10 more
    Java Result: 1
    public byte[] CmsEncrypt(byte[] message, KeyContainer keyContainer) throws NoSuchAlgorithmException, NoSuchProviderException, CMSException, IOException
    {
    Security.addProvider(new BouncyCastleProvider());
    X509Certificate cert = (X509Certificate) keyContainer.certificate;
    CMSEnvelopedDataGenerator gen = new CMSEnvelopedDataGenerator();
    gen.addKeyTransRecipient(cert);
    CMSProcessable data = new CMSProcessableByteArray(message);
    CMSEnvelopedData enveloped = gen.generate(data,
    CMSEnvelopedDataGenerator.AES128_CBC, "BC");

    return enveloped.getEncoded();

    }
    and this is my decryption code:
    public byte[] CmsDecrypt(byte[] cipher, KeyContainer keyContainer) throws CMSException, IOException, NoSuchProviderException
    {
    Security.addProvider(new BouncyCastleProvider());
    byte[] contents=null;
    CMSEnvelopedDataParser envelopedDataParser = new CMSEnvelopedDataParser(new ByteArrayInputStream(cipher));
    PrivateKey key = keyContainer.privateKey;
    X509Certificate cert = keyContainer.certificate;
    CMSEnvelopedData enveloped = new CMSEnvelopedData(cipher);
    Collection recip = enveloped.getRecipientInfos().getRecipients();
    KeyTransRecipientInformation rinfo = (KeyTransRecipientInformation) recip
    .iterator().next();
    if(keyContainer.provider.equals("Software"))
    contents = rinfo.getContent(
    new JceKeyTransEnvelopedRecipient(key).setProvider("BC"));
    else
    contents = rinfo.getContent(
    new JceKeyTransEnvelopedRecipient(key).setProvider("SunPKCS11-" + keyContainer.provider));
    System.out.println(new String(contents));
    return contents;

    }
    I must say that i use this token provider for cmsSign and cmsVerify and it works fine therefore i think the problem isn't for provider.
    this is my token configuration file:

    name = rainbow_token
    library = c:/windows/system32/dkck201.dll
    slotListIndex = 04
    attributes(*,CKO_PRIVATE_KEY,*) = {
    CKA_TOKEN = true

    }

    DB:2.60:Bouncycastle Pkcs#7 Encryption Problem cx

    I want to use BouncyCastle to encrypt and decrypt with pkcs7 format. I have a hardware token. when I use Keypair in jks file in my hard drive it work fine but when i use key pair in token its not work. this is my exception:
    Exception in thread "main" org.bouncycastle.cms.CMSException: cannot create cipher: No such algorithm: 2.16.840.1.101.3.4.1.2
    at org.bouncycastle.cms.jcajce.EnvelopedDataHelper.createCipher(Unknown Source)
    at org.bouncycastle.cms.jcajce.EnvelopedDataHelper$1.doInJCE(Unknown Source)
    at org.bouncycastle.cms.jcajce.EnvelopedDataHelper.execute(Unknown Source)
    at org.bouncycastle.cms.jcajce.EnvelopedDataHelper.createContentCipher(Unknown Source)
    at org.bouncycastle.cms.jcajce.JceKeyTransEnvelopedRecipient.getRecipientOperator(Unknown Source)
    at org.bouncycastle.cms.KeyTransRecipientInformation.getRecipientOperator(Unknown Source)
    at org.bouncycastle.cms.RecipientInformation.getContentStream(Unknown Source)
    at org.bouncycastle.cms.RecipientInformation.getContent(Unknown Source)
    at pktb.PKTB.CmsDecrypt(PKTB.java:288)
    at pktb.PKTB.main(PKTB.java:419)
    Caused by: java.security.NoSuchAlgorithmException: No such algorithm: 2.16.840.1.101.3.4.1.2
    at javax.crypto.Cipher.getInstance(DashoA13*..)
    at javax.crypto.Cipher.getInstance(DashoA13*..)
    at org.bouncycastle.jcajce.NamedJcaJceHelper.createCipher(Unknown Source)
    ... 10 more
    Java Result: 1
    public byte[] CmsEncrypt(byte[] message, KeyContainer keyContainer) throws NoSuchAlgorithmException, NoSuchProviderException, CMSException, IOException
    {
    Security.addProvider(new BouncyCastleProvider());
    X509Certificate cert = (X509Certificate) keyContainer.certificate;
    CMSEnvelopedDataGenerator gen = new CMSEnvelopedDataGenerator();
    gen.addKeyTransRecipient(cert);
    CMSProcessable data = new CMSProcessableByteArray(message);
    CMSEnvelopedData enveloped = gen.generate(data,
    CMSEnvelopedDataGenerator.AES128_CBC, "BC");

    return enveloped.getEncoded();

    }
    and this is my decryption code:
    public byte[] CmsDecrypt(byte[] cipher, KeyContainer keyContainer) throws CMSException, IOException, NoSuchProviderException
    {
    Security.addProvider(new BouncyCastleProvider());
    byte[] contents=null;
    CMSEnvelopedDataParser envelopedDataParser = new CMSEnvelopedDataParser(new ByteArrayInputStream(cipher));
    PrivateKey key = keyContainer.privateKey;
    X509Certificate cert = keyContainer.certificate;
    CMSEnvelopedData enveloped = new CMSEnvelopedData(cipher);
    Collection recip = enveloped.getRecipientInfos().getRecipients();
    KeyTransRecipientInformation rinfo = (KeyTransRecipientInformation) recip
    .iterator().next();
    if(keyContainer.provider.equals("Software"))
    contents = rinfo.getContent(
    new JceKeyTransEnvelopedRecipient(key).setProvider("BC"));
    else
    contents = rinfo.getContent(
    new JceKeyTransEnvelopedRecipient(key).setProvider("SunPKCS11-" + keyContainer.provider));
    System.out.println(new String(contents));
    return contents;

    }
    I must say that i use this token provider for cmsSign and cmsVerify and it works fine therefore i think the problem isn't for provider.
    this is my token configuration file:

    name = rainbow_token
    library = c:/windows/system32/dkck201.dll
    slotListIndex = 04
    attributes(*,CKO_PRIVATE_KEY,*) = {
    CKA_TOKEN = true

    }

  • RELEVANCY SCORE 2.59

    DB:2.59:Pki Certificates zf


    Hey Everyone...

    I'm having a few issues with some code, I'm fairly new to java and PKI. The code below is in a jsp page, and my intent is to grab the users name from the PKI certificate to use in a form, so that the user does not type in their username. The code below is not working, because certs is null when i try and view the page. My question is do I need to run this page on SSL to pull a PKI cert from the users computer?

    Any help or points in the right direction would be wonderful! Thanks!

    %@ page language="java" %
    %@ page import="java.security.cert.X509Certificate, java.security.cert.CertificateFactory" %

    %
    //String certificate = "";
    String explanation = "";
    String userDN = "";
    String issuerDN = "";

    X509Certificate certs[] = (X509Certificate[])request.getAttribute("javax.servlet.request.X509Certificate");

    if(certs != null) {
    userDn = certs[0].getSubjectDN().getName();
    issuerDN = certs[0].getIssuerDN().getName();
    explanation = "SubjectDN: " + userDN + "\nIssuerDN: " + issuerDN;
    }
    %

    DB:2.59:Pki Certificates zf

    firie

    I dunno, but try it over SSL... I'm sure there's no X509 in plain HTTP.

    and you've got a typo:

    String userDN = "";
    ....
    userDn = certs[0].getSubjectDN().getName();

  • RELEVANCY SCORE 2.58

    DB:2.58:Pkix Path Building Failed:Unable To Find Valid Certification Path To Reques cx


    public class Client {
    public static void main(String str[]) {
    if (downloadcertificate(.....))
    startConnection(.....);
    else
    System.out.println("Not able to download certificate");
    }
    private static boolean downloadcertificate(String host,int port)throws Exception {
    String hostip=host;
    char[] passphrase;
    String p ="changeit";
    passphrase = p.toCharArray();
    String cacertsFile;
    String fsep = System.getProperty("file.separator");
    String ROOT = System.getProperty("ROOT");
    if(ROOT==null || " ".equals(ROOT))
    throw new RuntimeException("Certificate file not available or ROOT path is not found");
    else
    cacertsFile=ROOT + fsep + "data" + fsep + "conf" + fsep + "SSL" + fsep + "cacerts";
    System.setProperty("javax.net.ssl.trustStore", cacertsFile);
    System.setProperty("javax.net.ssl.trustStoreType", "JKS");
    KeyStore ks = KeyStore.getInstance("JKS");
    InputStream in = null;
    OutputStream out=null;
    try{
    in = new FileInputStream(cacertsFile);
    ks.load(in, passphrase);

    SSLContext context = SSLContext.getInstance("TLS");
    TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509", "SunJSSE");
    tmf.init(ks);
    X509TrustManager defaultTrustManager = (X509TrustManager)tmf.getTrustManagers()[0];
    SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
    context.init(null, new TrustManager[] { tm }, null);

    SSLSocketFactory factory = context.getSocketFactory();
    SSLSocket socket = (SSLSocket)factory.createSocket(hostip, port);
    socket.setSoTimeout(10000);
    try
    {
    socket.startHandshake();
    socket.close();
    } catch (SSLException e) {
    e.printStackTrace(System.out);
    }
    X509Certificate[] chain = tm.chain;
    if (chain == null) {
    return false;
    }
    System.out.println("Server sent " + chain.length + " certificate(s):");
    MessageDigest sha1 = MessageDigest.getInstance("SHA1");
    MessageDigest md5 = MessageDigest.getInstance("MD5");
    int k=0;
    for (int i = 0; i chain.length; i++)
    {
    X509Certificate cert = chain;
    sha1.update(cert.getEncoded());
    md5.update(cert.getEncoded());
    k++;
    String alias=host;
    if(chain.length;1){
    alias = host + "-" + (k);
    }
    if(!ks.isCertificateEntry(alias))
    {
    ks.setCertificateEntry(alias, cert);
    }
    }
    out = new FileOutputStream(cacertsFile);
    ks.store(out, passphrase);
    }
    finally{
    if(out!= null){
    out.flush();
    out.close();
    }
    if(in!=null){
    in.close();
    }
    }
    return true;
    }

    private static Object startConnection(String host,String userid,String password,String Release,int port )throws Exception{
    String url= "https://"emhost/em":"emport/em"/services/Application";

    URL sourceurl = new URL(url);
    ApplicationServiceLocator servicelocator=new ApplicationServiceLocator();
    Application XML= servicelocator.getApplication(sourceurl);
    ((Stub) XML).setUsername(userid);
    ((Stub) XML).setPassword(password);
    if(!Release.equals(XML.getVersion())) /* Getting PKIX path validation error, In XML.getVersion() step */
    { }
    return XML;
    }
    private static class SavingTrustManager implements X509TrustManager {
    private final X509TrustManager tm;
    private X509Certificate[] chain;
    SavingTrustManager(X509TrustManager tm) {
    this.tm = tm;
    }
    public X509Certificate[] getAcceptedIssuers() {
    return null;
    }
    public void checkClientTrusted(X509Certificate[] chain, String authType) {
    this.chain = chain;
    }
    public void checkServerTrusted(X509Certificate[] chain, String authType) {
    this.chain = chain;
    }
    }
    }

    -------------------
    I am using the above client program to get certificate from server. This client program is getting and storing trusted entries into my trustStore, but the client is failing at the time of sending a request to server. The exception it is throwing is: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

    case 1:
    If I place original trustStore(cacerts, which java provides) and do the following:
    1. I am trying to connect server1, It will connect properly.
    2. If I try to connect server2, it will fail to connect.
    3. If I stop start JVM(my app), both servers got connected.

    case2:
    If I place original trustStore(cacerts, which java provides) and do the following:
    1. I am trying to connect server2, It will connect properly.
    2. If I try to connect server1, it will fail to connect.
    3. If I stop start JVM(my app), both servers got connected.

    In both cases certificate entries are getting stored properly and if I restart my application, I am able to connect to both the servers.

    Please provide your views why I am getting the exception when I am trying to connect to the second server in both the above cases. Why the JVM is not recognizing the second server's certificate ? Why the JVM is recognizing the certificate only if I do a restart the application ( My requirement is that I should not restart the application) ?

    Thanks In Advance,
    Vamsee.

    DB:2.58:Pkix Path Building Failed:Unable To Find Valid Certification Path To Reques cx

    I have already (a) told you that you can't; (b) asked you why you are doing this; and (c) told you that it is insecure.

    It would be unprofessional of me to provide you with assistance on an insecure design.

  • RELEVANCY SCORE 2.58

    DB:2.58:Convert X509certificate Into .P7b File cp


    I have a X509Certificate and I'd like to save it into a PKCS#7 .p7b file. Currently, I'm able to save it into a .cer file with the following code:

    private void writeCertificate(Writer writer,
    X509Certificate cert)
    throws Exception
    {
    writer.write(BEGIN_CERTIFICATE_MARKER);
    writer.write("\n");
    writer.write(new String(Base64.encode(cert.getEncoded())));
    writer.write("\n");
    writer.write(END_CERTIFICATE_MARKER);
    writer.close();
    } What do I need to do to save as a .p7b file instead?

    DB:2.58:Convert X509certificate Into .P7b File cp

    The CertPath class will do what you want. Create a CertPath with all the certificates you want in the PKCS#7 and call getEncoded with "PKCS7" as the parameter and you'll get a DER-encoded certificates-only PKCS#7 structure. If you want "pem", just base64 encode the byte array and add the appropriate header/footer.

    EDIT: and I'm an idiot...this topic is almost a year old...thanks for bringing this up for no good reason

    Edited by: dstutz on Oct 26, 2008 10:13 AM

  • RELEVANCY SCORE 2.58

    DB:2.58:Connecting(Ssl) Using Pkcs#7 Certificate ka


    I am a newbie and I hv no idea about connecting securely to a remote server by means of pkcs#7 certificate.

    I am providing the following java code which is used for the conection.

    The signature( to be generated in pkcs#7 format for a certificate) is hard coded here and the "String ip" is an example I.P. to give u an idea.

    public class APIBased {

    public static class DummyTrustManager implements X509TrustManager {

    public DummyTrustManager() {
    }

    public boolean isClientTrusted(X509Certificate cert[]) {
    return true;
    }

    public boolean isServerTrusted(X509Certificate cert[]) {
    return true;
    }

    public X509Certificate[] getAcceptedIssuers() {
    return new X509Certificate[0];
    }

    public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {

    }

    public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {

    }
    }
    public static class DummyHostnameVerifier implements HostnameVerifier {

    public boolean verify( String urlHostname, String certHostname ) {
    return true;
    }

    public boolean verify(String arg0, SSLSession arg1) {
    return true;
    }
    }
    public static void main(String[] args) {



    SSLContext sslcontext = null;
    try {
    sslcontext = SSLContext.getInstance("SSL");

    sslcontext.init(new KeyManager[0],
    new TrustManager[] { new DummyTrustManager() },
    new SecureRandom());
    } catch (NoSuchAlgorithmException e) {
    e.printStackTrace(System.err);
    } catch (KeyManagementException e) {
    e.printStackTrace(System.err);
    }

    SSLSocketFactory factory = sslcontext.getSocketFactory();

    String data="V00501^adsdsfff";
    String signature="MIIHvQYJKoZIhvcNAQcCoIIHrjCCB6oCAQExCzAJBgUrDgMCGgUAMAsGCSqGSIb3DQEHAaCCBaUwggWhMIIEiaADAgECAgI1qDANBgkqhkiG9w0BAQUFADCB0zEk=";
    String urlParameters="data=";
    try{

    urlParameters =urlParameters + URLEncoder.encode(data, "UTF-8") +"signature=" + URLEncoder.encode(signature, "UTF-8");
    }catch(Exception e){

    e.printStackTrace();

    }

    try{
    URL url;
    HttpsURLConnection connection;
    InputStream is = null;

    //------------------------

    String ip="45.168.64.6";
    url = new URL("https://" + ip + "/TIN/PanInquiryBackEnd");
    System.out.println("URL "+ip);

    connection = (HttpsURLConnection) url.openConnection();

    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");


    connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
    connection.setRequestProperty("Content-Language", "en-US");

    connection.setUseCaches (false);
    connection.setDoInput(true);
    connection.setDoOutput(true);

    connection.setSSLSocketFactory(factory);
    connection.setHostnameVerifier(new DummyHostnameVerifier());



    OutputStream os = connection.getOutputStream();
    OutputStreamWriter osw = new OutputStreamWriter(os);
    osw.write(urlParameters);
    osw.flush();
    osw.close();



    is =connection.getInputStream();

    BufferedReader in = new BufferedReader(new InputStreamReader(is));

    String line = in.readLine();

    System.out.println("Output "+line);
    is.close();
    in.close();

    } catch(Exception e){
    e.printStackTrace();
    }
    }

    }I have exported the certificate from
    Interner ExplorerToolsInternet OptionsContentsCerficates in abc.p7b file.
    My problem is, i hv no idea how to generate the siganture string within the code.

    Any kind of sugggestions and helps in this regard are most welcome.

    Thanking you all.........looking forward to a solution very soon.

    DB:2.58:Connecting(Ssl) Using Pkcs#7 Certificate ka

    There are two completely separate issues here.

    1. HTTPS, i.e. HTTP over SSL. See the Javadoc, Security, JSSE Reference Guide. That dummy trust manager is insecure. Don't use it. See above.

    2. Formatting the POST data with a pkcs#7 signature. I have no idea about that, sorry. I would try the Cryptography forum for that.

  • RELEVANCY SCORE 2.58

    DB:2.58:How To Use Client Side Certificate To Access The Soap Service sj


    HI,

    I am client side and need to access a remote SOAP server side using a certificate.

    I don't know how to add the certificate in my Java code, although I can get it using X509Certificate. The following is my code.

    Thanks for any help

    public class Dash911 {

    public static void main(String args[]) throws IOException {

    try {
    //I have a Cert class that generate the cert
    X509Certificate certificate = (new Cert()).getCertificate();

    String targetURI= "http://schemas.ecs.telefinity.com/webservices/postal/";
    String methodName = "FindStreet";
    String encodingStyleURI = Constants.NS_URI_SOAP_ENC;
    Vector params = new Vector();
    String[] names = {"Westcorp", "35805"};
    params.addElement(new Parameter("names", names.getClass(), names, null));
    String endpointURL = "https://prototype.test.telefinity.com/integrationprovisioning/postal.asmx";

    makeCall(targetURI, methodName, encodingStyleURI, null, params, endpointURL);

    } catch (Throwable t) {
    }
    }//main
    }

    Thanks a lot

    DB:2.58:How To Use Client Side Certificate To Access The Soap Service sj

    HI,

    I am client side and need to access a remote SOAP server side using a certificate.

    I don't know how to add the certificate in my Java code, although I can get it using X509Certificate. The following is my code.

    Thanks for any help

    public class Dash911 {

    public static void main(String args[]) throws IOException {

    try {
    //I have a Cert class that generate the cert
    X509Certificate certificate = (new Cert()).getCertificate();

    String targetURI= "http://schemas.ecs.telefinity.com/webservices/postal/";
    String methodName = "FindStreet";
    String encodingStyleURI = Constants.NS_URI_SOAP_ENC;
    Vector params = new Vector();
    String[] names = {"Westcorp", "35805"};
    params.addElement(new Parameter("names", names.getClass(), names, null));
    String endpointURL = "https://prototype.test.telefinity.com/integrationprovisioning/postal.asmx";

    makeCall(targetURI, methodName, encodingStyleURI, null, params, endpointURL);

    } catch (Throwable t) {
    }
    }//main
    }

    Thanks a lot

  • RELEVANCY SCORE 2.58

    DB:2.58:Help In Creating Digital Cetificate sc


    We are planning to create our own CA by using ikeyman from IBM . At the same time we want create a different Digital Certificates for each client so that they can use the certificate to talk to our server.

    I wrote a java program to do this , but i am not sure this is the correct way ..Please help me in assisting

    I don't know how to sign the certificate by CA programatically

    Thanks
    srinivas

    import java.security.*;
    import java.security.cert.Certificate;
    import java.security.cert.*;
    import java.security.spec.*;
    import java.io.*;
    import java.util.*;
    import java.math.*;
    import org.bouncycastle.x509.X509V3CertificateGenerator;
    import org.bouncycastle.jce.X509Principal;
    import org.bouncycastle.jce.provider.BouncyCastleProvider;

    public class ClientCertificates {

    static X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();
    static MessageDigest digester;
    static int counter =1;

    public static void main (String[] args) throws Exception {
    Security.addProvider(new BouncyCastleProvider());
    digester = MessageDigest.getInstance("MD5");
    KeyStore serverKeyStore = KeyStore.getInstance("JKS");

    // String keystoreFile = "FileTransfer.privateKS";
    FileInputStream fis;
    KeyStore ks1 = null;
    KeyPairGenerator KPGen = null;

    try {
    ks1 = KeyStore.getInstance("JKS");
    String keyPass = "startnow";
    char[] pwd = keyPass.toCharArray();
    fis = new FileInputStream("server.jks");
    ks1.load(fis,pwd);
    Enumeration e = ks1.aliases();
    while(e.hasMoreElements())
    {
    System.out.println((String)e.nextElement());
    }
    X509Certificate cert = (X509Certificate)ks1.getCertificate("server");

    X509Certificate clientCert = createClientCert();

    ks1.setCertificateEntry("client"+counter,clientCert);

    fis.close();
    FileOutputStream fos = new FileOutputStream("server.jks");
    ks1.store(fos,pwd);
    fos.close();

    } catch (FileNotFoundException e) {

    }
    }
    public static X509Certificate createClientCert()
    throws Exception
    {
    X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();
    KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA");
    kpGen.initialize(1024);
    KeyPair kpair = kpGen.generateKeyPair();

    //
    // issuer
    //
    String issuer = "CN=oagserver.csnt.csnet.gov, O=oagserver.csnt.csnet.gov, C=US";

    //
    // subjects name table.
    //
    Hashtable attrs = new Hashtable();
    Vector order = new Vector();
    counter++;
    attrs.put(X509Principal.C, "reddy"+counter);
    attrs.put(X509Principal.O, "reddy"+counter+".csnt.csnet.gov");
    attrs.put(X509Principal.L, "oag");
    attrs.put(X509Principal.CN, "reddy"+counter+".csnt.csnet.gov");
    attrs.put(X509Principal.EmailAddress, "testing@tester.org");

    order.addElement(X509Principal.C);
    order.addElement(X509Principal.O);
    order.addElement(X509Principal.L);
    order.addElement(X509Principal.CN);
    order.addElement(X509Principal.EmailAddress);

    v3CertGen.setSerialNumber(BigInteger.valueOf(20));
    v3CertGen.setIssuerDN(new X509Principal(issuer));
    v3CertGen.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30));
    v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 30)));
    v3CertGen.setSubjectDN(new X509Principal(order, attrs));
    v3CertGen.setPublicKey(kpair.getPublic());
    v3CertGen.setSignatureAlgorithm("SHA1WithRSAEncryption");

    X509Certificate cert = v3CertGen.generateX509Certificate(kpair.getPrivate());

    cert.checkValidity(new Date());

    printDigest(cert);

    return cert;
    }

    static void printDigest(X509Certificate certi) {
    byte[] sig = certi.getSignature();
    digester.update(sig);
    byte[] digest = digester.digest();
    for(int i = 0; i digest.length; i++)
    System.out.print(digest);
    System.out.println();
    }

    }

    DB:2.58:Help In Creating Digital Cetificate sc

    We are planning to create our own CA by using ikeyman from IBM . At the same time we want create a different Digital Certificates for each client so that they can use the certificate to talk to our server.

    I wrote a java program to do this , but i am not sure this is the correct way ..Please help me in assisting

    I don't know how to sign the certificate by CA programatically

    Thanks
    srinivas

    import java.security.*;
    import java.security.cert.Certificate;
    import java.security.cert.*;
    import java.security.spec.*;
    import java.io.*;
    import java.util.*;
    import java.math.*;
    import org.bouncycastle.x509.X509V3CertificateGenerator;
    import org.bouncycastle.jce.X509Principal;
    import org.bouncycastle.jce.provider.BouncyCastleProvider;

    public class ClientCertificates {

    static X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();
    static MessageDigest digester;
    static int counter =1;

    public static void main (String[] args) throws Exception {
    Security.addProvider(new BouncyCastleProvider());
    digester = MessageDigest.getInstance("MD5");
    KeyStore serverKeyStore = KeyStore.getInstance("JKS");

    // String keystoreFile = "FileTransfer.privateKS";
    FileInputStream fis;
    KeyStore ks1 = null;
    KeyPairGenerator KPGen = null;

    try {
    ks1 = KeyStore.getInstance("JKS");
    String keyPass = "startnow";
    char[] pwd = keyPass.toCharArray();
    fis = new FileInputStream("server.jks");
    ks1.load(fis,pwd);
    Enumeration e = ks1.aliases();
    while(e.hasMoreElements())
    {
    System.out.println((String)e.nextElement());
    }
    X509Certificate cert = (X509Certificate)ks1.getCertificate("server");

    X509Certificate clientCert = createClientCert();

    ks1.setCertificateEntry("client"+counter,clientCert);

    fis.close();
    FileOutputStream fos = new FileOutputStream("server.jks");
    ks1.store(fos,pwd);
    fos.close();

    } catch (FileNotFoundException e) {

    }
    }
    public static X509Certificate createClientCert()
    throws Exception
    {
    X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();
    KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA");
    kpGen.initialize(1024);
    KeyPair kpair = kpGen.generateKeyPair();

    //
    // issuer
    //
    String issuer = "CN=oagserver.csnt.csnet.gov, O=oagserver.csnt.csnet.gov, C=US";

    //
    // subjects name table.
    //
    Hashtable attrs = new Hashtable();
    Vector order = new Vector();
    counter++;
    attrs.put(X509Principal.C, "reddy"+counter);
    attrs.put(X509Principal.O, "reddy"+counter+".csnt.csnet.gov");
    attrs.put(X509Principal.L, "oag");
    attrs.put(X509Principal.CN, "reddy"+counter+".csnt.csnet.gov");
    attrs.put(X509Principal.EmailAddress, "testing@tester.org");

    order.addElement(X509Principal.C);
    order.addElement(X509Principal.O);
    order.addElement(X509Principal.L);
    order.addElement(X509Principal.CN);
    order.addElement(X509Principal.EmailAddress);

    v3CertGen.setSerialNumber(BigInteger.valueOf(20));
    v3CertGen.setIssuerDN(new X509Principal(issuer));
    v3CertGen.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30));
    v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 30)));
    v3CertGen.setSubjectDN(new X509Principal(order, attrs));
    v3CertGen.setPublicKey(kpair.getPublic());
    v3CertGen.setSignatureAlgorithm("SHA1WithRSAEncryption");

    X509Certificate cert = v3CertGen.generateX509Certificate(kpair.getPrivate());

    cert.checkValidity(new Date());

    printDigest(cert);

    return cert;
    }

    static void printDigest(X509Certificate certi) {
    byte[] sig = certi.getSignature();
    digester.update(sig);
    byte[] digest = digester.digest();
    for(int i = 0; i digest.length; i++)
    System.out.print(digest);
    System.out.println();
    }

    }

  • RELEVANCY SCORE 2.57

    DB:2.57:Reading Private Key From File c3


    Can some tell me why I'm I getting "NULL POINTER EXCEPTION" in the following code when I try to print the retrived private key ? I'm able to retrieve the public key though.
    Thanks.

    Here is the code.

    import java.io.*;
    import java.security.*;
    import java.security.cert.*;
    import javax.crypto.*;
    import org.bouncycastle.jce.provider.BouncyCastleProvider;
    import java.util.*;

    public class cert
    {
    public static void main(String[] args) throws InvalidKeyException,NoSuchPaddingException,CertificateException,UnrecoverableKeyException,NoSuchAlgorithmException,NoSuchProviderException,IOException,KeyStoreException,FileNotFoundException
    {
    String keyStoreFile = "c:/docume~1/ydamle.menlo/.keystore";
    String password = "test123";
    String alias = "mykey";
    String strToEncrypt = "This is a test";
    String encryptedFile = "g:/java/code/encryptedFile.txt";
    String decryptedFile = "g:/java/code/decryptedFile.txt";

    Security.addProvider(new BouncyCastleProvider());
    // try
    //{
    if(new File(keyStoreFile).exists() new File(keyStoreFile).canRead())
    {
    KeyStore keyStore = KeyStore.getInstance("JKS","SUN");
    keyStore.load(new FileInputStream(new File(keyStoreFile)),password.toCharArray());
    //System.out.println("Creation Date : " + keyStore.getCreationDate(alias));
    //System.out.println("Certificate : " + keyStore.getCertificate(alias));

    X509Certificate cert = (X509Certificate) keyStore.getCertificate(alias);
    PublicKey pubKey = cert.getPublicKey();
    Key privKey = keyStore.getKey(alias,password.toCharArray());
    System.out.println("private key : " + privKey.getAlgorithm());
    System.out.println("Pub Key : " + pubKey.getFormat());
    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.ENCRYPT_MODE,pubKey);
    byte[] array = strToEncrypt.getBytes();
    CipherOutputStream COS = new CipherOutputStream(
    new FileOutputStream(encryptedFile),cipher);

    COS.write(array);
    COS.close();

    cipher.init(Cipher.DECRYPT_MODE,privKey);
    CipherInputStream CIS = new CipherInputStream(
    new FileInputStream(encryptedFile),cipher);

    CIS.read(array);
    CIS.close();

    String decryptedStr = array.toString();
    PrintWriter BOS = new PrintWriter(
    new FileWriter(
    new File(decryptedFile)));
    BOS.write(decryptedStr);
    BOS.close();
    }
    else
    {
    System.out.println(" ERROR: File NOT Found - " + keyStoreFile);
    }
    // }
    // catch(KeyStoreException kse){}
    // catch(FileNotFoundException fnfe){}
    // catch(IOException ioe){}
    // catch(NoSuchProviderException nsp){}
    // catch(NoSuchAlgorithmException nsae){}
    // catch(UnrecoverableKeyException uke){}
    // catch(CertificateException ce){}
    }

    }

    DB:2.57:Reading Private Key From File c3

    I haven't run your code to see what's happening, but I wrote som code yesterday that might be useful to you. It reads the public and private key, respectively, from a file:

    private PublicKey ReadPublicKeyFromFile() {
    PublicKey publicKey = null;

    try {
    DataInputStream in = new DataInputStream(
    new FileInputStream("public.key"));
    byte[] encodedPublicKey = new byte[1024];
    in.read(encodedPublicKey);
    in.close();

    X509EncodedKeySpec encodedPublicKeySpec = new X509EncodedKeySpec(encodedPublicKey);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA", "BC");
    publicKey = keyFactory.generatePublic(encodedPublicKeySpec);
    } catch (Exception e) {
    System.out.println(e.toString());
    e.printStackTrace();
    }

    return publicKey;
    }

    private PrivateKey ReadPrivateKeyFromFile() {
    PrivateKey privateKey = null;

    try {
    DataInputStream in = new DataInputStream(
    new FileInputStream("private.key"));
    byte[] encodedPrivateKey = new byte[1024];
    int noOfBytes = in.read(encodedPrivateKey);
    in.close();

    PKCS8EncodedKeySpec encodedPrivateKeySpec = new PKCS8EncodedKeySpec(encodedPrivateKey);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA", "BC");
    privateKey = keyFactory.generatePrivate(encodedPrivateKeySpec);
    } catch (Exception e) {
    System.out.println(e.toString());
    e.printStackTrace();
    }

    return privateKey;
    }

    Hope this helps,
    Magnus

  • RELEVANCY SCORE 2.57

    DB:2.57:Storing Crl In "Windows-My" 1s


    Hi all,

    I am using Java 6's SunMSCAPI to store and retrieve x509 certificates.

    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(filePath));
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    cert = (X509Certificate)cf.generateCertificate (bis);
    KeyStore ks = KeyStore.getInstance("Windows-MY");
    ks.load(null, null) ;
    ks.setCertificateEntry(alias, cert);
    bis.close();

    This works fine, But I have to store a x509 CRL also in "WIndows-MY".
    The problem is KeyStore does not have a method to set a CRL entry.
    Is there some other way I can store a CRL in "WIndows-MY".

    Thanks.

    DB:2.57:Storing Crl In "Windows-My" 1s

    I thought if there is some way to store crl in a way similar to store cert i can use it, but I guess its not. I will have to try some other way.

    Thanks for your help!!!

  • RELEVANCY SCORE 2.57

    DB:2.57:X509certificate In Java And Javax - Whats The Difference? 3s


    Hi,

    I wonder about the two same named classes X509Certificate in
    java.security.cert and javax.security.cert .
    Is there any difference?

    Olek

  • RELEVANCY SCORE 2.57

    DB:2.57:Problem With Cipher.Init() 9j


    i am using java 1.4.2 on Windows 2000 Professional

    I am using "Assembla" as JCE Provider for Microsoft Keystore. But when i call Cipher.init() i am getting the following error

    MSKeyStoreJNI: Could not acquire context for temporary container used for importing public key.
    SYSMSG: The keyset is not defined.

    The Code is as follow :
    -----------------------------import java.util.*;
    import javax.crypto.*;
    import java.security.*;
    import java.security.cert.*;
    import se.assembla.jce.provider.ms.*;
    // JCE Provider for Microsoft Keystore https://download.assembla.se

    public class cipher
    {
    public cipher(String[] args) throws Exception
    {
    Security.addProvider(new MSProvider());

    KeyStore ks = KeyStore.getInstance("msks", "assembla");
    ks.load(null,null);

    X509Certificate cert = null;
    String alias = null;

    for(Enumeration e = ks.aliases(); e.hasMoreElements();)
    {
    alias = (String) e.nextElement();

    if(ks.isKeyEntry(alias))
    {
    cert = (java.security.cert.X509Certificate) ks.getCertificate(alias);
    break;
    }
    }

    Cipher c = Cipher.getInstance("RSA", "assembla");

    c.init(Cipher.ENCRYPT_MODE, cert); // error on this line

    }
    public static void main(String args[])
    {
    try
    {
    new cipher(args);
    }
    catch(Exception e)
    {
    e.printStackTrace();
    }
    }
    }--- hasstar
    --- [SCJP]
    --- url : http://www.myjavaserver.com/~hasstar

    DB:2.57:Problem With Cipher.Init() 9j

    Yes, I tried KeyStore ks = KeyStore.getInstance("RSA", "assembla"); instead of msks?
    and it is not working. (www.bouncycastle.org)

    I tried www.bouncycastle.org, but i don't know how to get Certificates from Microsoft Keystore.

    If u know how to get keys from Microsoft Keystore please help

  • RELEVANCY SCORE 2.57

    DB:2.57:X509certificate Include A Password In Visual Studio 2003?? 1j


    Hi, We have a requirment to load a certificate into a vs 2003 vb.net application, I have written a test container in vs2008 and used the following code:
    Dim cert As New X509Certificate(C:\certificates\mycert.cer, password)However, the password parameter is not available under .NET 2003, can some one please give me an equivilant 2003 version of this?Many thanksMike.

    DB:2.57:X509certificate Include A Password In Visual Studio 2003?? 1j

    Hi, We have a requirment to load a certificate into a vs 2003 vb.net application, I have written a test container in vs2008 and used the following code:
    Dim cert As New X509Certificate(C:\certificates\mycert.cer, password)However, the password parameter is not available under .NET 2003, can some one please give me an equivilant 2003 version of this?Many thanksMike.

  • RELEVANCY SCORE 2.57

    DB:2.57:My Way Of Validating Certificate Chain - What Do U Think? aa


    Hi,

    I need to control ssl handshake process through validating peer's certificate against my CUSTOM truststore (i'm providing a path to it and creating java class KeyStore)
    In the following method I just return true if I find peer's certificate (any in his chain) in my own truststore, what do u thing about it? Need to improve, how?

    public boolean certificateCallback( X509Certificate[] peerCertChain , int arg1 ) {

    SetX509Certificate trustedSet = KeyStores.getTrustedCerts(trustStore);
    IteratorX509Certificate it = trustedSet.iterator();
    boolean trusted = false;
    do {
    X509Certificate cert = it.next();
    //TODO ask/check if we need this for
    for (int i=0;ipeerCertChain.length;i++){
    if (cert.equals(peerCertChain))
    trusted=true;
    }
    if ( trusted ) {
    log.debug("Found trusted! Peer certificate:" + peerCertChain[0] + ", trustedCertificate" + cert.toString());
    }
    } while (it.hasNext() !trusted);

    return trusted;

    DB:2.57:My Way Of Validating Certificate Chain - What Do U Think? aa

    Hi,

    I need to control ssl handshake process through validating peer's certificate against my CUSTOM truststore (i'm providing a path to it and creating java class KeyStore)
    In the following method I just return true if I find peer's certificate (any in his chain) in my own truststore, what do u thing about it? Need to improve, how?

    public boolean certificateCallback( X509Certificate[] peerCertChain , int arg1 ) {

    SetX509Certificate trustedSet = KeyStores.getTrustedCerts(trustStore);
    IteratorX509Certificate it = trustedSet.iterator();
    boolean trusted = false;
    do {
    X509Certificate cert = it.next();
    //TODO ask/check if we need this for
    for (int i=0;ipeerCertChain.length;i++){
    if (cert.equals(peerCertChain))
    trusted=true;
    }
    if ( trusted ) {
    log.debug("Found trusted! Peer certificate:" + peerCertChain[0] + ", trustedCertificate" + cert.toString());
    }
    } while (it.hasNext() !trusted);

    return trusted;

  • RELEVANCY SCORE 2.57

    DB:2.57:Request Parameter Not Found dj



    Trying to do: @RequestParameter ( "javax.servlet.request.X509Certificate" ) private X509Certificate[] userCerts;And the cert is in the request:Request key: javax.servlet.request.X509Certificate value: [Ljava.security.cert.X509Certificate;@155ec9f4But it is brought into my ejb3 as null... if ( userCerts == null ) { /* no certs no access */ System.out.println ( "No client cert injected" ); return "NO_CLIENT_CERTS"; }I always get the "No client cert injected" debug...Any ideas what I did / am doing wrong?

    DB:2.57:Request Parameter Not Found dj


    If you are try to inject this into a session bean you have to declare the seam interceptor - either by using the @Interceptor-Annotation or by using components.xml.Regardsfhh

  • RELEVANCY SCORE 2.56

    DB:2.56:"Validity Interval Out Of Date" Exception zm


    I am trying to query my OCSP server to check certificate status. If I use openssl to do this with the same server URL and same certificate, it works. But I need to do it in Java. CRLs are being properly issued every hour also.

    When I run my code, I get:

    java.security.cert.CertPathValidatorException: java.io.IOException: Response is unreliable: its validity interval is out-of-date
    at sun.security.provider.certpath.PKIXMasterCertPathValidator.validate(PKIXMasterCertPathValidator.java:139)
    at sun.security.provider.certpath.PKIXCertPathValidator.doValidate(PKIXCertPathValidator.java:316)
    at sun.security.provider.certpath.PKIXCertPathValidator.engineValidate(PKIXCertPathValidator.java:178)
    at java.security.cert.CertPathValidator.validate(CertPathValidator.java:250)
    at OCSPtest.OCSPtest.main(OCSPtest.java:127)I have the CA cert as a trusted ca cert in my jre.lib/security/cacerts file, and I have the strng encryption extensions installed.

    Here is the code:
    package OCSPtest;

    //~--- JDK imports ------------------------------------------------------------

    import java.io.*;

    import java.net.URI;

    import java.security.*;
    import java.security.cert.*;
    import java.security.cert.PKIXParameters;
    import java.security.cert.X509Certificate;

    import java.util.*;

    /**
    * Class description
    *
    *
    * @version Enter version here..., 07/10/15
    * @author Enter your name here...
    */
    public class OCSPtest{

    /**
    * Check the revocation status of a public key certificate using OCSP.
    */

    /*
    * Filename that contains the OCSP server's cert.
    */
    private static final String OCSP_SERVER_CERT =
    "/Users/jar/certs/OCSPSignerCertificate.pem";

    /*
    * Filename that contains the root CA cert of the OCSP server's cert.
    */
    private static final String ROOT_CA_CERT =
    "/Users/jar/certs/SensorNetCA.pem";

    /**
    * Checks the revocation status of a public key certificate using OCSP.
    *
    * Usage: java ValidateCert cert-file [OCSP-server]
    * cert-file is the filename of the certificate to be checked.
    * The certificate must be in PEM format.
    * OCSP-server is the URL of the OCSP server to use.
    * If not supplied then the certificate must identify an OCSP
    * server by means of its AuthorityInfoAccess extension.
    * If supplied then it overrides any URL which may be present
    * in the certificate's AuthorityInfoAccess extension.
    *
    * Example: java \
    * -Dhttp.proxyHost=proxy.example.net \
    * -Dhttp.proxyPort=8080 \
    * ValidateCert \
    * mycert.pem \
    * http://ocsp.openvalidation.org:80
    */
    public static void main(String[] args) {
    try {
    CertPath cp = null;
    Vector certs = new Vector();
    URI ocspServer = null;
    String ocspServerString =
    "https://ca2.sensornet.gov:8442/ejbca/publicweb/status/ocsp";

    /*
    * if (args.length == 0 || args.length 2) {
    * System.out.println(
    * "Usage: java ValidateCert cert-file [OCSP-server]");
    * System.exit(-1);
    * }
    */

    // load the cert to be checked
    certs.add(
    getCertFromFile(
    "/Users/jar/certs/jarSensornet.cer"));

    // handle location of OCSP server
    ocspServer = new URI(ocspServerString);
    System.out.println("Using the OCSP server at: ca2");
    System.out.println("to check the revocation status of: "
    + certs.elementAt(0));
    System.out.println();

    // init cert path
    CertificateFactory cf = CertificateFactory.getInstance("X509");
    cp = (CertPath) cf.generateCertPath(certs);

    // load the root CA cert for the OCSP server cert
    X509Certificate rootCACert = getCertFromFile(ROOT_CA_CERT);

    // init trusted certs
    TrustAnchor ta = new TrustAnchor(rootCACert, null);
    Set trustedCertsSet = new HashSet();

    trustedCertsSet.add(ta);

    // init cert store
    // Set certSet = new HashSet();
    // X509Certificate ocspCert = getCertFromFile(OCSP_SERVER_CERT);
    //System.out.println("OCSP Responder cert: " + ocspCert);
    //certSet.add(ocspCert);

    // init PKIX parameters
    PKIXParameters params = null;

    params = new PKIXParameters(trustedCertsSet);
    //params.addCertStore(store);

    // enable OCSP
    Security.setProperty("ocsp.enable", "true");

    if (ocspServer != null) {
    Security.setProperty("ocsp.responderURL", ocspServerString);
    // Security.setProperty(
    // "ocsp.responderCertSubjectName",
    // ocspCert.getSubjectX500Principal().getName());
    }

    // perform validation
    CertPathValidator cpv =
    CertPathValidator.getInstance("PKIX");
    PKIXCertPathValidatorResult cpv_result =
    (PKIXCertPathValidatorResult) cpv.validate(cp, params);
    X509Certificate trustedCert =
    (X509Certificate) cpv_result.getTrustAnchor().getTrustedCert();

    if (trustedCert == null) {
    System.out.println("Trsuted Cert = NULL");
    } else {
    System.out.println("Trusted CA DN = "
    + trustedCert.getSubjectDN());
    }
    } catch (CertPathValidatorException e) {
    e.printStackTrace();
    System.exit(1);
    } catch (Exception e) {
    e.printStackTrace();
    System.exit(-1);
    }

    System.out.println("CERTIFICATE VALIDATION SUCCEEDED");
    System.exit(0);
    }

    /**
    * Read a certificate from the specified filepath.
    */
    private static X509Certificate getCertFromFile(String path) {
    X509Certificate cert = null;

    try {
    File certFile = new File(path);

    if (!certFile.canRead()) {
    throw new IOException(" File " + certFile.toString()
    + " is unreadable");
    }

    FileInputStream fis = new FileInputStream(path);
    CertificateFactory cf = CertificateFactory.getInstance("X509");

    cert = (X509Certificate) cf.generateCertificate(fis);
    } catch (Exception e) {
    System.out.println("Can't construct X509 Certificate. " + path
    + " " + e.getMessage());
    }

    return cert;
    }
    }

    DB:2.56:"Validity Interval Out Of Date" Exception zm

    Err, no they're not. The validity interval is out of date on at least one of them. This is the only rational deduction from the evidence. Try printing out the notBefore and notAfter dates and see.

  • RELEVANCY SCORE 2.56

    DB:2.56:Signature Exception 91


    When I try to use the verify(Public key) method I get an exception saying: Signature does not match. What may be the reasons. Also I have a certificate which says that I have aprivate key with this certificate. What does it mean? How can I retrieve the private key from that certificate . I need to use that private key to decrypt my data.

    pss.. I already have a certificate provided. Please let me know how to get the private key associated with that certificate although as far as i know getting the private key from a cert is not possible..Plz reply back ASAP..its real urgent

    THis is my sample code:

    /*
    * Created on Oct 11, 2007
    *
    * TODO To change the template for this generated file go to
    * Window - Preferences - Java - Code Style - Code Templates
    */
    package com.aetna.ebs.pa.disability.getdcdetail.transporter;

    import java.io.ByteArrayInputStream;
    import java.io.Serializable;
    import java.io.FileInputStream;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.security.KeyStore;
    import java.security.MessageDigest;
    import java.security.Principal;
    import java.security.PrivateKey;
    import java.security.PublicKey;
    import java.security.SignatureException;
    import java.security.cert.CertificateFactory;

    import javax.crypto.BadPaddingException;
    import javax.crypto.Cipher;
    import java.security.cert.X509Certificate;
    import java.io.*;

    //import com.ibm.etools.webservice.wscommonbnd.X509Certificate;
    import com.ibm.jvm.util.ByteArrayOutputStream;

    /**
    * @author n178578
    *
    * TODO To change the template for this generated type comment go to
    * Window - Preferences - Java - Code Style - Code Templates
    */
    public class TestEncrypyDecrypt implements Serializable {
    ObjectInputStream ois;
    private KeyStore myStore = null;

    public ObjectInputStream encrypt(Serializable obj) throws Exception
    {
    try{
    FileInputStream inStream = new FileInputStream("C:/userfold/aaaa.cer");
    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    X509Certificate cert = (X509Certificate)cf.generateCertificate(inStream);
    inStream.close();

    MessageDigest md = MessageDigest.getInstance("SHA1");

    md.update(getBytes(obj));

    byte[] msgDigest = md.digest();

    String a = cert.getSigAlgName();
    String y = cert.getSigAlgOID();
    String z = cert.getType();
    Principal dn = cert.getSubjectDN();

    byte[] b = cert.getEncoded();

    PublicKey d = cert.getPublicKey();
    try{
    cert.verify(d);
    }
    catch(SignatureException msg){
    System.out.println("Signature Exception:"+msg);
    }
    Cipher cipher =Cipher.getInstance("RSA/ECB/PKCS1Padding","IBMJCE"); //Hardcoded temporarily
    //cipher = Cipher.getInstance("e");

    //byte[] byteCrypted = cipher.doFinal(msgDigest);

    cipher.init(Cipher.ENCRYPT_MODE,cert);
    byte[] byteCrypted = cipher.doFinal(msgDigest);
    System.out.println("Source crypted: "+new String(byteCrypted)+"\n");

    File inFile = new File("C://Documents and Settings//user//.keystore");

    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(new FileInputStream(inFile),"123456".toCharArray());

    String alias = "xxx3";
    PrivateKey pk = (PrivateKey) ks.getKey(alias,"123456".toCharArray() );
    System.out.println("Private Key"+ pk.toString());

    Cipher rsaCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding","IBMJCE");

    rsaCipher.init(Cipher.DECRYPT_MODE,pk);
    try{
    byte[] decrypt = rsaCipher.doFinal(byteCrypted);
    }
    catch(BadPaddingException bpe)
    {
    System.out.println("reason"+bpe);
    }

    ByteArrayInputStream bais = new ByteArrayInputStream(byteCrypted);
    ois = new ObjectInputStream(bais);
    }

    catch(Exception e)
    {
    e.printStackTrace();
    }

    return ois;
    }
    public static byte[] getBytes(Object obj) throws IOException
    {
    try
    {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(bos);
    System.out.println("Class Name"+ obj.getClass());
    oos.writeObject(obj);
    oos.flush();
    oos.close();
    bos.close();
    byte [] data = bos.toByteArray();
    return data;
    }

    catch(Exception e)
    {
    e.printStackTrace();
    }
    return null;
    }

    }

    DB:2.56:Signature Exception 91

    When I try to use the verify(Public key) method I get an exception saying: Signature does not match. What may be the reasons. Also I have a certificate which says that I have aprivate key with this certificate. What does it mean? How can I retrieve the private key from that certificate . I need to use that private key to decrypt my data.

    pss.. I already have a certificate provided. Please let me know how to get the private key associated with that certificate although as far as i know getting the private key from a cert is not possible..Plz reply back ASAP..its real urgent

    THis is my sample code:

    /*
    * Created on Oct 11, 2007
    *
    * TODO To change the template for this generated file go to
    * Window - Preferences - Java - Code Style - Code Templates
    */
    package com.aetna.ebs.pa.disability.getdcdetail.transporter;

    import java.io.ByteArrayInputStream;
    import java.io.Serializable;
    import java.io.FileInputStream;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.security.KeyStore;
    import java.security.MessageDigest;
    import java.security.Principal;
    import java.security.PrivateKey;
    import java.security.PublicKey;
    import java.security.SignatureException;
    import java.security.cert.CertificateFactory;

    import javax.crypto.BadPaddingException;
    import javax.crypto.Cipher;
    import java.security.cert.X509Certificate;
    import java.io.*;

    //import com.ibm.etools.webservice.wscommonbnd.X509Certificate;
    import com.ibm.jvm.util.ByteArrayOutputStream;

    /**
    * @author n178578
    *
    * TODO To change the template for this generated type comment go to
    * Window - Preferences - Java - Code Style - Code Templates
    */
    public class TestEncrypyDecrypt implements Serializable {
    ObjectInputStream ois;
    private KeyStore myStore = null;

    public ObjectInputStream encrypt(Serializable obj) throws Exception
    {
    try{
    FileInputStream inStream = new FileInputStream("C:/userfold/aaaa.cer");
    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    X509Certificate cert = (X509Certificate)cf.generateCertificate(inStream);
    inStream.close();

    MessageDigest md = MessageDigest.getInstance("SHA1");

    md.update(getBytes(obj));

    byte[] msgDigest = md.digest();

    String a = cert.getSigAlgName();
    String y = cert.getSigAlgOID();
    String z = cert.getType();
    Principal dn = cert.getSubjectDN();

    byte[] b = cert.getEncoded();

    PublicKey d = cert.getPublicKey();
    try{
    cert.verify(d);
    }
    catch(SignatureException msg){
    System.out.println("Signature Exception:"+msg);
    }
    Cipher cipher =Cipher.getInstance("RSA/ECB/PKCS1Padding","IBMJCE"); //Hardcoded temporarily
    //cipher = Cipher.getInstance("e");

    //byte[] byteCrypted = cipher.doFinal(msgDigest);

    cipher.init(Cipher.ENCRYPT_MODE,cert);
    byte[] byteCrypted = cipher.doFinal(msgDigest);
    System.out.println("Source crypted: "+new String(byteCrypted)+"\n");

    File inFile = new File("C://Documents and Settings//user//.keystore");

    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(new FileInputStream(inFile),"123456".toCharArray());

    String alias = "xxx3";
    PrivateKey pk = (PrivateKey) ks.getKey(alias,"123456".toCharArray() );
    System.out.println("Private Key"+ pk.toString());

    Cipher rsaCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding","IBMJCE");

    rsaCipher.init(Cipher.DECRYPT_MODE,pk);
    try{
    byte[] decrypt = rsaCipher.doFinal(byteCrypted);
    }
    catch(BadPaddingException bpe)
    {
    System.out.println("reason"+bpe);
    }

    ByteArrayInputStream bais = new ByteArrayInputStream(byteCrypted);
    ois = new ObjectInputStream(bais);
    }

    catch(Exception e)
    {
    e.printStackTrace();
    }

    return ois;
    }
    public static byte[] getBytes(Object obj) throws IOException
    {
    try
    {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(bos);
    System.out.println("Class Name"+ obj.getClass());
    oos.writeObject(obj);
    oos.flush();
    oos.close();
    bos.close();
    byte [] data = bos.toByteArray();
    return data;
    }

    catch(Exception e)
    {
    e.printStackTrace();
    }
    return null;
    }

    }

  • RELEVANCY SCORE 2.55

    DB:2.55:Error Exception Filenotfoundexception 3k


    Hi all!
    I try to read the content of a file but i have the following error:

    java.io.FileNotFoundException: C:\DeviceP\certs\ca.cert (Impossibile trovare il file specificato.
    )
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.init(FileInputStream.java:103)
    at java.io.FileInputStream.init(FileInputStream.java:63)
    at ConnectionThread.readCaKey(ConnectionThread.java:128)
    at ConnectionThread.connect(ConnectionThread.java:84)
    at ConnectionThread.run(ConnectionThread.java:60)
    at java.lang.Thread.startup(Thread.java:753)

    the code is:

    private PublicKey readCaKey() {
    FileInputStream fis;
    try {
    fis=new FileInputStream("C:/DeviceP/certs/ca.cert");
    byte[] cert=Util.readCompleteStream(fis);
    X509Certificate caCert=new X509Certificate(cert);
    PublicKey pk=caCert.getPublicKey();
    return pk;
    } catch (Exception ex) {
    ex.printStackTrace();
    return null;
    }

    The file ca.cert exists in the directory c:\DeviceP\certs.

    Please help me!!!

    DB:2.55:Error Exception Filenotfoundexception 3k

    hey there,
    well according to what i have read in your code,
    i think the problem is when u are using the..: Util.readCompleteStream(fis);

    i think you should use the - java.io.BufferedInputStream

    the error is occurring because of the function readCompleteStream, the BufferedInputStream will work the same as the other one...

    please do check the java.io.* library...
    reply back to carloso24@hotmail.com so i can know if the error is fixed....
    thank you...
    waiting your reply for more help don't hesitate to ask me.. bye

  • RELEVANCY SCORE 2.53

    DB:2.53:Verify Digital Signature Produced By Sap Content Server Http 4.5 Interface 9a



    I am trying to verify a digital signature sent by the SAP Content Server HTTP 4.5 Interface.

    In the Java code I am using the class SsfDataPKCS7 - verify method, and it always returns 'false'.

    Within the SAP system, using, say, ABAP function SCMS_HTTP_DELETE; I can see the Input data for signing is

    O112300123DCN%3DMNDT,OU%3DDEV,O%3DMANDANT,C%3DGB20070928133751

    length = 62

    -

    The signed data created by SAP , passed as secKey is like

    MIIBIwYJKoZIhvcNAQcCoIIBFDCCARACAQExCzAJBgUrDgMCGgUAMAsGCSqGSIb3DQEHATGB8DCB7QIBATBBMDwxCzAJBgNVBAYTAkdCMRAwDgYDVQQKEwdNQU5EQU5UMQwwCgYDVQQLEwNERVYxDTALBgNVBAMTBE1ORFQCAQAwCQYFKw4DAhoFAKBdMBgGCSqGSIb3DQEJAzELBgkqhkiG9w0BBwEwHAYJKoZIhvcNAQkFMQ8XDTA3MTAwNDA3NDk0MVowIwYJKoZIhvcNAQkEMRYEFGh5aRofeHPzk%2BjFbBsCsuEtX5J8MAkGByqGSM44BAMEMDAuAhUAizCHFWp1ZZ7hB8fumtocONiSa84CFQCcb2YG7hyDJ8J9oIZbZAXDlRqgEw%3D%3D

    ( we then decode %2B back to +, %2F back to /, %3D back to = )

    The Java code is -

    boolean res = true;

    // Load the certificate.

    InputStream inStream = new FileInputStream("Mandant_Certificate.crt");

    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    X509Certificate cert = (X509Certificate)cf.generateCertificate(inStream);

    inStream.close();

    // This is the secKey as received from R/3, with URL-encoded characters decoded.

    String base64SecKey = "MIIBIgYJKoZIhvcNAQcCoIIBEzCCAQ8CAQExCzAJBgUrDgMCGgUAMAsGCSqGSIb3DQEHATGB7zCB7AIBATBBMDwxCzAJBgNVBAYTAkdCMRAwDgYDVQQKEwdNQU5EQU5UMQwwCgYDVQQLEwNERVYxDTALBgNVBAMTBE1ORFQCAQAwCQYFKw4DAhoFAKBdMBgGCSqGSIb3DQEJAzELBgkqhkiG9w0BBwEwHAYJKoZIhvcNAQkFMQ8XDTA3MDkyNzA4NTQxNFowIwYJKoZIhvcNAQkEMRYEFB1ATpscjBqU/2HDYcJudhZ53Z6CMAkGByqGSM44BAMELzAtAhRetJmrmyFY25zNrcr2WFBRJMucAIVAKIhF5dTEsIiXuIoaspohWnR86T";

    // Decode the secKey from base64.

    byte[] secKey = Base64.decode(base64SecKey);

    // Load the secKey into an SsfDataPKCS7.

    SsfDataPKCS7 secKeyData = new SsfDataPKCS7(new ByteArrayInputStream(secKey));

    // Build an address book with our certificate in it.

    ISsfPab pab = new SsfPabBasicImpl(new X509Certificate[]);

    // Build the message. These are the parameter values from same URL

    // that secKey came from.

    String message = "O11200120DESCRDCN%3DMNDT,OU%3DDEV,O%3DMANDANT,C%3DGB20070927105414";

    ISsfData messageData = new SsfDataPKCS7(new ByteArrayInputStream(message.getBytes()));

    // Verify the signature. This prints "false".

    SsfSigRcpList signer = new SsfSigRcpList();

    try {

    res = secKeyData.verify(pab, signer, messageData, cert);

    } catch (SsfInvalidDataException e){

    System.out.println("Error while verifying data "+e);

    }

    Has anyone already had this problem and solved it ?

    Can anyone help me ?

    Thank you in advance,

    Andy

    DB:2.53:Verify Digital Signature Produced By Sap Content Server Http 4.5 Interface 9a


    Solution -

    The Turgraz library has a different idea of what a X509Certificate object is ,

    which is not compatible with Sun's idea.

    So - import iaik.x509.X509Certificate;

    and then

    // Load the certificate.

    InputStream inStream = new FileInputStream("Certificate.crt");

    X509Certificate cert = new X509Certificate(inStream);

    then it works.

  • RELEVANCY SCORE 2.53

    DB:2.53:Certpathvalidatorexception: Its Validity Interval Is Out Of Date am


    I am trying to query my OCSP server to check certificate validity. My CA is EJBCA. I checked the clocks on my client and the server, and they are within a few seconds of each other. But when my code runs, I get:

    java.security.cert.CertPathValidatorException: java.io.IOException: Response is unreliable: its validity interval is out-of-date
    at sun.security.provider.certpath.PKIXMasterCertPathValidator.validate(PKIXMasterCertPathValidator.java:139)
    at sun.security.provider.certpath.PKIXCertPathValidator.doValidate(PKIXCertPathValidator.java:316)
    at sun.security.provider.certpath.PKIXCertPathValidator.engineValidate(PKIXCertPathValidator.java:178)
    at java.security.cert.CertPathValidator.validate(CertPathValidator.java:206)
    at validatecertuseocsp.ValidateCertUseOCSP.main(ValidateCertUseOCSP.java:120)I cannot find anything on what this means or how to fix it. My CA is issuing CRLs, every hour, and their time validity is correct. Here is the code I am trying (which I got from Sun):

    /*
    * Main.java
    *
    * Created on Oct 12, 2007, 3:21:59 PM
    *
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    */

    package validatecertuseocsp;

    import java.io.*;
    import java.net.URI;
    import java.security.*;
    import java.security.cert.*;
    import java.util.*;
    import java.security.cert.X509Certificate;
    import java.security.cert.PKIXParameters;

    /**
    * Check the revocation status of a public key certificate using OCSP.
    */

    public class ValidateCertUseOCSP {

    /*
    * Filename that contains the root CA cert of the OCSP server's cert.
    */
    private static final String ROOT_CA_CERT = "/opt/jboss/Certificates/SensorNetCA.pem";

    /*
    * Filename that contains the OCSP server's cert.
    */
    private static final String OCSP_SERVER_CERT = "/opt/jboss/Certificates/OCSPSignerCertificate.pem";

    /**
    * Checks the revocation status of a public key certificate using OCSP.
    *
    * Usage: java ValidateCert cert-file [OCSP-server]
    * cert-file is the filename of the certificate to be checked.
    * The certificate must be in PEM format.
    * OCSP-server is the URL of the OCSP server to use.
    * If not supplied then the certificate must identify an OCSP
    * server by means of its AuthorityInfoAccess extension.
    * If supplied then it overrides any URL which may be present
    * in the certificate's AuthorityInfoAccess extension.
    *
    * Example: java \
    * -Dhttp.proxyHost=proxy.example.net \
    * -Dhttp.proxyPort=8080 \
    * ValidateCert \
    * mycert.pem \
    * http://ocsp.openvalidation.org:80
    */
    public static void main(String[] args) {
    try {
    CertPath cp = null;
    Vector certs = new Vector();
    URI ocspServer = null;
    /*
    if (args.length == 0 || args.length 2) {
    System.out.println(
    "Usage: java ValidateCert cert-file [OCSP-server]");
    System.exit(-1);
    }
    */
    // load the cert to be checked
    certs.add(getCertFromFile("/Users/jar/Documents/keys/jarSensornet.cer"));

    // handle location of OCSP server
    if (args.length == 2) {
    ocspServer = new URI(
    "https://ca2.sensornet.gov:8442/ejbca/publicweb/webdist/certdist?cmd=crlissuer=CN%3DSensorNetCA%2CDC%3Dsensornet%2CDC%3Dgov");
    System.out.println("Using the OCSP server at: ca2");
    System.out.println("to check the revocation status of: " +
    certs.elementAt(0));
    System.out.println();
    } else {
    System.out.println("Using the OCSP server specified in the " +
    "cert to check the revocation status of: " +
    certs.elementAt(0));
    System.out.println();
    }

    // init cert path
    CertificateFactory cf = CertificateFactory.getInstance("X509");
    cp = (CertPath)cf.generateCertPath(certs);

    // load the root CA cert for the OCSP server cert
    X509Certificate rootCACert = getCertFromFile(ROOT_CA_CERT);

    // init trusted certs
    TrustAnchor ta = new TrustAnchor(rootCACert, null);
    Set trustedCertsSet = new HashSet();
    trustedCertsSet.add(ta);

    // init cert store
    Set certSet = new HashSet();
    X509Certificate ocspCert = getCertFromFile(OCSP_SERVER_CERT);
    certSet.add(ocspCert);
    CertStoreParameters storeParams =
    new CollectionCertStoreParameters(certSet);
    CertStore store = CertStore.getInstance("Collection", storeParams);

    // init PKIX parameters
    PKIXParameters params = null;
    params = new PKIXParameters(trustedCertsSet);
    params.addCertStore(store);

    // enable OCSP
    Security.setProperty("ocsp.enable", "true");
    if (ocspServer != null) {
    Security.setProperty("ocsp.responderURL", args[1]);
    Security.setProperty("ocsp.responderCertSubjectName",
    ocspCert.getSubjectX500Principal().getName());
    }

    // perform validation
    CertPathValidator cpv = CertPathValidator.getInstance("PKIX");
    PKIXCertPathValidatorResult cpv_result =
    (PKIXCertPathValidatorResult) cpv.validate(cp, params);
    X509Certificate trustedCert = (X509Certificate)
    cpv_result.getTrustAnchor().getTrustedCert();

    if (trustedCert == null) {
    System.out.println("Trsuted Cert = NULL");
    } else {
    System.out.println("Trusted CA DN = " +
    trustedCert.getSubjectDN());
    }

    } catch (CertPathValidatorException e) {
    e.printStackTrace();
    System.exit(1);

    } catch(Exception e) {
    e.printStackTrace();
    System.exit(-1);
    }
    System.out.println("CERTIFICATE VALIDATION SUCCEEDED");
    System.exit(0);
    }

    /*
    * Read a certificate from the specified filepath.
    */
    private static X509Certificate getCertFromFile(String path) {
    X509Certificate cert = null;
    try {

    File certFile = new File(path);
    if (!certFile.canRead())
    throw new IOException(" File " + certFile.toString() +
    " is unreadable");

    FileInputStream fis = new FileInputStream(path);
    CertificateFactory cf = CertificateFactory.getInstance("X509");
    cert = (X509Certificate)cf.generateCertificate(fis);

    } catch(Exception e) {
    System.out.println("Can't construct X509 Certificate. " + path + " " +
    e.getMessage());
    }
    return cert;
    }
    }

    DB:2.53:Certpathvalidatorexception: Its Validity Interval Is Out Of Date am

    Well, I found a few errors in this. It is still not working, but the validity interval is not the problem.

  • RELEVANCY SCORE 2.53

    DB:2.53:Javaplugin Applets Don't Work If You Require Client-Cert Authentication kz


    Our whole organization is about to start using Java SmartCards for everything in the near future. (DoD's common access card.) I foresee enormous problems for applications that are currently using applets in them as a result unless something is done to fix a bug in the next version of the plugin.

    This link below is in reference to a bug which Sun seems to believe is fixed and closed.

    http://developer.java.sun.com/developer/bugParade/bugs/4681247.html

    I am posting here, because I believe that postings against this bug will never be read by anyone. Here is a short explaination of the problem:

    The Java Plugin cannot download archives when the web server requires client side certificates. The fix is to tell the plugin where your certificate file is at. This recommended fix is bad if you are using software certs, because you don't have 1 certificate for all of the internet sites for which you need a cert. It also tells you to type your cert password in the clear on the filesystem so that the plugin can find it.

    But most importantly, this advice is totally useless if you are using hard token certs such as .... JavaCards. PKCS11 modules are not files. They are plugins that supply the algorithms that are going to be done securely in the smartcard. This means that you cannot lock down a web server based application to require a smartcard if that application is using applets. The plugin needs to use the exact same protocol to download the archive as it used to get the applet tag that requires it.

    In the same vein, it was an irritating experience to get some JavaCards and after much work come to the conclusion that the design of the JSSE makes it incompatible with JavaCard for client/server style applications. (Somebody tell me that you have a JSSE compliant toolkit in which you can make a standalone Java Application that opens up SSL connections to servers and can use a JavaCard resident certificate to do so. It seems that you have to resort to a third-party library to use JavaCard certs with JSSE) Too many APIs are still being designed to assume that security modules consist of a set of X509Certificate/PrivateKey pairs in which you can extract the private key out of the module, and supply it to an encryption or a signing algorithm. With hardware tokens, you can only assume that security modules consist of a X509Certificate, and a method that will do the encryption/signature. And this method does NOT take the private key as an argument.... the private key is buried into the module as part of the that method's definition.

    Anyway, it appeared that the pleas relating to this issue are not being heard because the issue has been closed. This is a BIG deal for organizations who are now starting to actually PKI enable their existing applications - which often involve applets.

    DB:2.53:Javaplugin Applets Don't Work If You Require Client-Cert Authentication kz

    I commiserate.

    I believe the heavy reliance on the javax.net.ssl.keyStore system property is just wrong. An applet-local key manager for client-certificates would be really helpful.

    The current (1.4) plugin design includes its own certificate management ui (control panel). I feel this is wrong design. Why is there no upcall available from the applet framework into the host/browser's certificate management? The same sort of thing happened with the move from awt to swing. The not-invented-here mentality? What's next, a special java filesystem? :) Luckily applets are normally kept away from files, but with the impending service-oriented world, with certificates being passed about like Amoeba capabilities, better integration of the plugin with the host's security management is going to be a sore need.

  • RELEVANCY SCORE 2.53

    DB:2.53:Problem: Publickey And X509certificate pk


    Dear Java Experts:

    Please help with extracting the PublicKey out of an X509Certificate!

    I have a file with the name certificate.cer which contains an
    X.509Certificate. When I invoke the Certificate Browser of my
    operating system, I can see all the parts of this certificate
    including the public key.

    My Java applet can read this file certificate.cer, and it can
    show a text representation of this certificate, but it cannot
    show the public key.

    Can you tell me how to get the public key, the public exponent
    and the modulus? In the Java API I have found some methods called
    getPublicKey(), getPublicExponent() and getModulus(),
    but I do not understand whether they are what I need and how to
    deploy them.

    // The code snippet is:
    String filename = "certificate.cer"
    FileInputStream fis = new FileInputStream(filename);
    BufferedInputStream bis = new BufferedInputStream(fis);
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    while (bis.available() 0)
    {
    Certificate cert = cf.generateCertificate(bis);
    }

    Many thanks for your help
    M.K.Unger
    mkunger@go.com

    DB:2.53:Problem: Publickey And X509certificate pk

    Dear Daniel:

    Thank you very much! Now my applets works fine.

    Kind Regards
    M.K.Unger

  • RELEVANCY SCORE 2.53

    DB:2.53:How To Create X509 Certificate In Wp8 aa


    I want to create X509 certificate from MyCertificate.cer file (its self signed certificate created using Bouncycastle library in java)which I added in my project root directory.
    X509Certificate objx509= new X509Certificate(MyCertificate.cer);

    But I am getting exception as file not found.

    DB:2.53:How To Create X509 Certificate In Wp8 aa

    thats a typo mistake. But I am writing as
    X509Certificate objx509= new X509Certificate(RootCA_cert1.cer);

  • RELEVANCY SCORE 2.53

    DB:2.53:Basecertloginmodule Failure: Certificate Credentials Are Not a9



    When I try to use the BaseCertLoginModule, it fails with this error:
    Don't know how to obtain X509Certificate from: class java.lang.StringI looked at the source code and the failure occurs when the getAliasAndCert() method tries to read a X509 cert from ObjectCallback.getCredential(). Somehow the client cert is not being loaded in the credentials when the callback is done. Here is my login-config.xml; it is almost exactly as given in the manual: login-module code="org.jboss.security.auth.spi.BaseCertLoginModule"
    flag = "required"
    module-option name="password-stacking"useFirstPass/module-option
    module-option name="securityDomain"java:/jaas/encrypt-keystore-password/module-option
    module-option name="unauthenticatedIdentity"guest/module-option
    module-option name="verifier"org.jboss.security.auth.certs.AnyCertVerifier/module-option
    /login-module

    DB:2.53:Basecertloginmodule Failure: Certificate Credentials Are Not a9


    I too have this error, but the simple fix is beyond me... can anyone offer any advice? Thanks.

  • RELEVANCY SCORE 2.53

    DB:2.53:Performance Monitor Error At Getservercertificate 8a


    Hello,

    I just downloaded ans installed last version of BEA Performance Monitor for WLS 8.1. My WebLogic is in a development environment, with no license. At console startup, I get the following error:

    Exception encountered while processing content in console extension:
    javax.servlet.ServletException: weblogic.security.service.SSLManager.getServerCertificate(Lweblogic/security/u
    tils/SSLContextWrapper;)[Ljavax/security/cert/X509Certificate;
    at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:469)
    at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:463)
    at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:315)
    at weblogic.servlet.internal.RequestDispatcherImpl.include(RequestDispatcherImpl.java:638)
    at weblogic.servlet.internal.RequestDispatcherImpl.include(RequestDispatcherImpl.java:423)
    at weblogic.management.console.tags.IncludeTag.doDispatcherInclude(IncludeTag.java:121)
    at weblogic.management.console.tags.IncludeTag.doStartTag(IncludeTag.java:83)
    at weblogic.management.console.tags.ExtensibleTagDelegate.doExtensions(ExtensibleTagDelegate.java:192)

    at weblogic.management.console.tags.ExtensibleTagDelegate.doExtensionContent(ExtensibleTagDelegate.jav
    a:171)
    at weblogic.management.console.tags.nav.NavNodeTag.doEndTag(NavNodeTag.java:141)
    at weblogic.management.console.webapp._domain.__nav._jspService(__nav.java:2060)
    at weblogic.servlet.jsp.JspBase.service(JspBase.java:33)
    at weblogic.servlet.internal.ServletStubImpl$ServletInvocationAction.run(ServletStubImpl.java:1006)
    at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:419)
    at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:315)
    at weblogic.servlet.internal.RequestDispatcherImpl.forward(RequestDispatcherImpl.java:322)
    at weblogic.servlet.jsp.PageContextImpl.forward(PageContextImpl.java:150)
    at weblogic.management.console.actions.ForwardAction.perform(ForwardAction.java:35)
    at weblogic.management.console.actions.internal.ActionServlet.doAction(ActionServlet.java:173)
    at weblogic.management.console.actions.internal.ActionServlet.doGet(ActionServlet.java:91)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:740)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
    at weblogic.servlet.internal.ServletStubImpl$ServletInvocationAction.run(ServletStubImpl.java:1006)
    at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:419)
    at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:315)
    at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.jav
    a:6718)
    at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
    at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:121)
    at weblogic.servlet.internal.WebAppServletContext.invokeServlet(WebAppServletContext.java:3764)
    at weblogic.servlet.internal.ServletRequestImpl.execute(ServletRequestImpl.java:2644)
    at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:219)
    at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:178)
    --------------- nested within: ------------------
    weblogic.management.console.utils.NestedJspException: weblogic.security.service.SSLManager.getServerCertificat
    e(Lweblogic/security/utils/SSLContextWrapper;)[Ljavax/security/cert/X509Certificate; - with nested exception:
    [javax.servlet.ServletException: weblogic.security.service.SSLManager.getServerCertificate(Lweblogic/security/
    utils/SSLContextWrapper;)[Ljavax/security/cert/X509Certificate;]
    at weblogic.management.console.tags.IncludeTag.doStartTag(IncludeTag.java:86)
    at weblogic.management.console.tags.ExtensibleTagDelegate.doExtensions(ExtensibleTagDelegate.java:192)

    at weblogic.management.console.tags.ExtensibleTagDelegate.doExtensionContent(ExtensibleTagDelegate.jav
    a:171)
    at weblogic.management.console.tags.nav.NavNodeTag.doEndTag(NavNodeTag.java:141)
    at weblogic.management.console.webapp._domain.__nav._jspService(__nav.java:2060)
    at weblogic.servlet.jsp.JspBase.service(JspBase.java:33)
    at weblogic.servlet.internal.ServletStubImpl$ServletInvocationAction.run(ServletStubImpl.java:1006)
    at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:419)
    at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:315)
    at weblogic.servlet.internal.RequestDispatcherImpl.forward(RequestDispatcherImpl.java:322)
    at weblogic.servlet.jsp.PageContextImpl.forward(PageContextImpl.java:150)
    at weblogic.management.console.actions.ForwardAction.perform(ForwardAction.java:35)
    at weblogic.management.console.actions.internal.ActionServlet.doAction(ActionServlet.java:173)
    at weblogic.management.console.actions.internal.ActionServlet.doGet(ActionServlet.java:91)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:740)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
    at weblogic.servlet.internal.ServletStubImpl$ServletInvocationAction.run(ServletStubImpl.java:1006)
    at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:419)
    at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:315)
    at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.jav
    a:6718)
    at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
    at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:121)
    at weblogic.servlet.internal.WebAppServletContext.invokeServlet(WebAppServletContext.java:3764)
    at weblogic.servlet.internal.ServletRequestImpl.execute(ServletRequestImpl.java:2644)
    at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:219)
    at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:178)

    At administrative server startup, the following information (for reference) appears:

    04/06/2005 22:11:04 CEST Info WebLogicServer BEA-000377 Starting WebLogic Server with Java HotSpot(TM
    ) Client VM Version 1.4.2_05-b04 from Sun Microsystems Inc.
    04/06/2005 22:11:04 CEST Info Configuration Management BEA-150016 This server is being started as the
    administration server.
    04/06/2005 22:11:04 CEST Info Management BEA-141107 Version: WebLogic Server 8.1 SP4 Mon Nov 29 16:2
    1:29 PST 2004 471647
    WebLogic XMLX Module 8.1 SP4 Mon Nov 29 16:21:29 PST 2004 471647
    04/06/2005 22:11:04 CEST Notice Management BEA-140005 Loading domain configuration from configuration
    repository at E:\dat\workplace\weblogic\mydomain\.\config.xml.
    04/06/2005 22:11:06 CEST Notice Log Management BEA-170019 The server log file E:\dat\workplace\weblog
    ic\mydomain\myserver\myserver.log is opened. All server side log events will be written to this file.
    04/06/2005 22:11:07 CEST Notice Security BEA-090082 Security initializing using security realm myreal
    m.
    04/06/2005 22:11:07 CEST Notice WebLogicServer BEA-000327 Starting WebLogic Admin Server "myserver" f
    or domain "mydomain"
    ClassLoaderIPre-processor com.dirig.preprocessor.DirigBEAClassProcessor loaded and initialized
    04/06/2005 22:11:11 CEST Notice WebLogicServer BEA-000331 Started WebLogic Admin Server "myserver" fo
    r domain "mydomain" running in Development Mode
    04/06/2005 22:11:11 CEST Notice WebLogicServer BEA-000360 Server started in RUNNING mode
    04/06/2005 22:11:11 CEST Notice WebLogicServer BEA-000355 Thread "ListenThread.Default" listening on
    port 7001, ip address *.*
    04/06/2005 22:11:32 CEST Notice Security BEA-090170 Loading the private key stored under the alias De
    moIdentity from the jks keystore file E:\bin\computing\software\engineering\server\application\WebLogic\bin\se
    rver\lib\DemoIdentity.jks.

    Could anybody tell me what I am doing wrong? I rechecked several times the documentaion and can't see any step i didn't follow during installation.

    Thank you in advance.

    Dimas

    DB:2.53:Performance Monitor Error At Getservercertificate 8a

    Hello,

    I just downloaded ans installed last version of BEA Performance Monitor for WLS 8.1. My WebLogic is in a development environment, with no license. At console startup, I get the following error:

    Exception encountered while processing content in console extension:
    javax.servlet.ServletException: weblogic.security.service.SSLManager.getServerCertificate(Lweblogic/security/u
    tils/SSLContextWrapper;)[Ljavax/security/cert/X509Certificate;
    at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:469)
    at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:463)
    at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:315)
    at weblogic.servlet.internal.RequestDispatcherImpl.include(RequestDispatcherImpl.java:638)
    at weblogic.servlet.internal.RequestDispatcherImpl.include(RequestDispatcherImpl.java:423)
    at weblogic.management.console.tags.IncludeTag.doDispatcherInclude(IncludeTag.java:121)
    at weblogic.management.console.tags.IncludeTag.doStartTag(IncludeTag.java:83)
    at weblogic.management.console.tags.ExtensibleTagDelegate.doExtensions(ExtensibleTagDelegate.java:192)

    at weblogic.management.console.tags.ExtensibleTagDelegate.doExtensionContent(ExtensibleTagDelegate.jav
    a:171)
    at weblogic.management.console.tags.nav.NavNodeTag.doEndTag(NavNodeTag.java:141)
    at weblogic.management.console.webapp._domain.__nav._jspService(__nav.java:2060)
    at weblogic.servlet.jsp.JspBase.service(JspBase.java:33)
    at weblogic.servlet.internal.ServletStubImpl$ServletInvocationAction.run(ServletStubImpl.java:1006)
    at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:419)
    at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:315)
    at weblogic.servlet.internal.RequestDispatcherImpl.forward(RequestDispatcherImpl.java:322)
    at weblogic.servlet.jsp.PageContextImpl.forward(PageContextImpl.java:150)
    at weblogic.management.console.actions.ForwardAction.perform(ForwardAction.java:35)
    at weblogic.management.console.actions.internal.ActionServlet.doAction(ActionServlet.java:173)
    at weblogic.management.console.actions.internal.ActionServlet.doGet(ActionServlet.java:91)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:740)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
    at weblogic.servlet.internal.ServletStubImpl$ServletInvocationAction.run(ServletStubImpl.java:1006)
    at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:419)
    at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:315)
    at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.jav
    a:6718)
    at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
    at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:121)
    at weblogic.servlet.internal.WebAppServletContext.invokeServlet(WebAppServletContext.java:3764)
    at weblogic.servlet.internal.ServletRequestImpl.execute(ServletRequestImpl.java:2644)
    at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:219)
    at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:178)
    --------------- nested within: ------------------
    weblogic.management.console.utils.NestedJspException: weblogic.security.service.SSLManager.getServerCertificat
    e(Lweblogic/security/utils/SSLContextWrapper;)[Ljavax/security/cert/X509Certificate; - with nested exception:
    [javax.servlet.ServletException: weblogic.security.service.SSLManager.getServerCertificate(Lweblogic/security/
    utils/SSLContextWrapper;)[Ljavax/security/cert/X509Certificate;]
    at weblogic.management.console.tags.IncludeTag.doStartTag(IncludeTag.java:86)
    at weblogic.management.console.tags.ExtensibleTagDelegate.doExtensions(ExtensibleTagDelegate.java:192)

    at weblogic.management.console.tags.ExtensibleTagDelegate.doExtensionContent(ExtensibleTagDelegate.jav
    a:171)
    at weblogic.management.console.tags.nav.NavNodeTag.doEndTag(NavNodeTag.java:141)
    at weblogic.management.console.webapp._domain.__nav._jspService(__nav.java:2060)
    at weblogic.servlet.jsp.JspBase.service(JspBase.java:33)
    at weblogic.servlet.internal.ServletStubImpl$ServletInvocationAction.run(ServletStubImpl.java:1006)
    at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:419)
    at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:315)
    at weblogic.servlet.internal.RequestDispatcherImpl.forward(RequestDispatcherImpl.java:322)
    at weblogic.servlet.jsp.PageContextImpl.forward(PageContextImpl.java:150)
    at weblogic.management.console.actions.ForwardAction.perform(ForwardAction.java:35)
    at weblogic.management.console.actions.internal.ActionServlet.doAction(ActionServlet.java:173)
    at weblogic.management.console.actions.internal.ActionServlet.doGet(ActionServlet.java:91)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:740)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
    at weblogic.servlet.internal.ServletStubImpl$ServletInvocationAction.run(ServletStubImpl.java:1006)
    at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:419)
    at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:315)
    at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.jav
    a:6718)
    at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
    at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:121)
    at weblogic.servlet.internal.WebAppServletContext.invokeServlet(WebAppServletContext.java:3764)
    at weblogic.servlet.internal.ServletRequestImpl.execute(ServletRequestImpl.java:2644)
    at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:219)
    at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:178)

    At administrative server startup, the following information (for reference) appears:

    04/06/2005 22:11:04 CEST Info WebLogicServer BEA-000377 Starting WebLogic Server with Java HotSpot(TM
    ) Client VM Version 1.4.2_05-b04 from Sun Microsystems Inc.
    04/06/2005 22:11:04 CEST Info Configuration Management BEA-150016 This server is being started as the
    administration server.
    04/06/2005 22:11:04 CEST Info Management BEA-141107 Version: WebLogic Server 8.1 SP4 Mon Nov 29 16:2
    1:29 PST 2004 471647
    WebLogic XMLX Module 8.1 SP4 Mon Nov 29 16:21:29 PST 2004 471647
    04/06/2005 22:11:04 CEST Notice Management BEA-140005 Loading domain configuration from configuration
    repository at E:\dat\workplace\weblogic\mydomain\.\config.xml.
    04/06/2005 22:11:06 CEST Notice Log Management BEA-170019 The server log file E:\dat\workplace\weblog
    ic\mydomain\myserver\myserver.log is opened. All server side log events will be written to this file.
    04/06/2005 22:11:07 CEST Notice Security BEA-090082 Security initializing using security realm myreal
    m.
    04/06/2005 22:11:07 CEST Notice WebLogicServer BEA-000327 Starting WebLogic Admin Server "myserver" f
    or domain "mydomain"
    ClassLoaderIPre-processor com.dirig.preprocessor.DirigBEAClassProcessor loaded and initialized
    04/06/2005 22:11:11 CEST Notice WebLogicServer BEA-000331 Started WebLogic Admin Server "myserver" fo
    r domain "mydomain" running in Development Mode
    04/06/2005 22:11:11 CEST Notice WebLogicServer BEA-000360 Server started in RUNNING mode
    04/06/2005 22:11:11 CEST Notice WebLogicServer BEA-000355 Thread "ListenThread.Default" listening on
    port 7001, ip address *.*
    04/06/2005 22:11:32 CEST Notice Security BEA-090170 Loading the private key stored under the alias De
    moIdentity from the jks keystore file E:\bin\computing\software\engineering\server\application\WebLogic\bin\se
    rver\lib\DemoIdentity.jks.

    Could anybody tell me what I am doing wrong? I rechecked several times the documentaion and can't see any step i didn't follow during installation.

    Thank you in advance.

    Dimas

  • RELEVANCY SCORE 2.53

    DB:2.53:Get X509certificate With Tomcat ? d9



    Hi,i'm using jboss 3.0 with tomcat 4.0.3, and i have configure tomcat (tomcat4-service.xml) to accept ssl connections. I'm using a client that is connecting to the tomcat and that is presenting his certificate. There is no problem with the connection, but when i try to get the information of the certificate in the servlet:X509Certificate cert = (X509Certificate) httpRequest.getAttribute("javax.servlet.request.X509Certificate");the variable cert is always null.Any idea ? Do i have to export any variables in the tomcat configuration file (if yes, how can i do that) ?Thanks very much for your helpRegards.david

    DB:2.53:Get X509certificate With Tomcat ? d9


    this is the correct castjava.security.cert.X509Certificate [] certs = (java.security.cert.X509Certificate[]) request.getAttribute("javax.servlet.request.X509Certificate");

  • RELEVANCY SCORE 2.53

    DB:2.53:Jaas Jaznusermanager &Amp;&Amp; Ssl Client Certificate Integration 1f


    Hi at all,

    I'm developing a Web Application with JDEVELOPER 10g.
    I deploy it on Standalone OC4J 9.0.4.
    I have configured Client Certificate Authentication (mutual)

    I'm working to integrate JAAS (JAZNUserManager XML-BASED) with SSL Client Certificate Authentication (NON SSO).
    I want to make a complete application without Protocol-Based interferences towards J2EE Standard.

    My idea is this:
    When a user, with a X509Certificate (common CA to the server) want become a member :

    -Send a form
    -
    1// retrieving of JAAS provider
    2 JAZNUserManager usrMgr =(JAZNUserManager) this.getServletContext().getAttribute("user.manager");
    3 // insert entry in the repository (jazn-data.xml)
    4 User user=usrMgr.createUser(username,password);
    5// retrieving the client certificate supplied in the SSL handshake phase

    6 X509Certificate cert=(X509Certificate) request.getAttribute("java.security.cert.X509Certificate");

    7 // association client certificate withe the new user.
    8 user.setCertificate (cert);

    9 //mapping the user with its security role appropriate (MemberRegistered in this example)

    10 user.addTogroup(usrMgr.getGroup("MemberRegistered"));

    11//store the new entry in the repository.
    12 usrMgr.store();

    .....
    ........ other business operation.

    My problems are:

    1. When usrMgr.store() is issued, repository (jazn-data.xml doesn't update!!!! Why? )
    2. request.getattribute("java.security.cert.X509Certificate") is null!!!! Why ? How may I solve this

    This area (JAZNUserManager) have not enough documentation.
    Where can I found it.
    For example Javadoc of JAAS Oracle Provider API.

    Thanks

    DB:2.53:Jaas Jaznusermanager &Amp;&Amp; Ssl Client Certificate Integration 1f

    Hi at all,

    I'm developing a Web Application with JDEVELOPER 10g.
    I deploy it on Standalone OC4J 9.0.4.
    I have configured Client Certificate Authentication (mutual)

    I'm working to integrate JAAS (JAZNUserManager XML-BASED) with SSL Client Certificate Authentication (NON SSO).
    I want to make a complete application without Protocol-Based interferences towards J2EE Standard.

    My idea is this:
    When a user, with a X509Certificate (common CA to the server) want become a member :

    -Send a form
    -
    1// retrieving of JAAS provider
    2 JAZNUserManager usrMgr =(JAZNUserManager) this.getServletContext().getAttribute("user.manager");
    3 // insert entry in the repository (jazn-data.xml)
    4 User user=usrMgr.createUser(username,password);
    5// retrieving the client certificate supplied in the SSL handshake phase

    6 X509Certificate cert=(X509Certificate) request.getAttribute("java.security.cert.X509Certificate");

    7 // association client certificate withe the new user.
    8 user.setCertificate (cert);

    9 //mapping the user with its security role appropriate (MemberRegistered in this example)

    10 user.addTogroup(usrMgr.getGroup("MemberRegistered"));

    11//store the new entry in the repository.
    12 usrMgr.store();

    .....
    ........ other business operation.

    My problems are:

    1. When usrMgr.store() is issued, repository (jazn-data.xml doesn't update!!!! Why? )
    2. request.getattribute("java.security.cert.X509Certificate") is null!!!! Why ? How may I solve this

    This area (JAZNUserManager) have not enough documentation.
    Where can I found it.
    For example Javadoc of JAAS Oracle Provider API.

    Thanks

  • RELEVANCY SCORE 2.52

    DB:2.52:How I Do Oracle See A Interface Java In A Java Source ms


    Hi

    I created a java source that references a java interface javax.xml.crypto.AlgorithmMethod but when I compiled my java source the erros occurs:
    JS_X509KEYSELECTOR:36: cannot access javax.xml.crypto.AlgorithmMethod.

    JS_X509KEYSELECTOR is my java source. I create it in onwer CSNOTAFISCAL and contains:

    import java.io.IOException;
    import java.security.Key;
    import java.security.KeyStore;
    import java.security.KeyStoreException;
    import java.security.PublicKey;
    import java.security.cert.Certificate;
    import java.security.cert.CertificateFactory;
    import java.security.cert.CertSelector;
    import java.security.cert.X509Certificate;
    import java.security.cert.X509CertSelector;
    import java.util.Enumeration;
    import java.util.Iterator;
    import javax.security.auth.x500.X500Principal;
    import javax.xml.crypto.*;
    import javax.xml.crypto.dsig.*;
    import javax.xml.crypto.dsig.keyinfo.*;

    /**
    *
    * @author Ednei Parmigiani Jnior-
    */
    public class X509KeySelector extends KeySelector {

    private KeyStore ks;

    public X509KeySelector(KeyStore keyStore) throws KeyStoreException {
    if (keyStore == null) {
    throw new NullPointerException("keyStore is null");
    }
    this.ks = keyStore;

    this.ks.size();
    }

    public KeySelectorResult select(KeyInfo keyInfo,
    KeySelector.Purpose purpose, AlgorithmMethod method,
    XMLCryptoContext context) throws KeySelectorException {

    SignatureMethod sm = (SignatureMethod) method;

    try {
    if (keyInfo == null || ks.size() == 0) {
    return new SimpleKeySelectorResult(null);
    }

    Iterator i = keyInfo.getContent().iterator();
    while (i.hasNext()) {
    XMLStructure kiType = (XMLStructure) i.next();

    if (kiType instanceof X509Data) {
    X509Data xd = (X509Data) kiType;
    KeySelectorResult ksr = x509DataSelect(xd, sm);
    if (ksr != null) {
    return ksr;
    }

    } else if (kiType instanceof KeyName) {
    KeyName kn = (KeyName) kiType;
    Certificate cert = ks.getCertificate(kn.getName());
    if (cert != null algEquals(sm.getAlgorithm(),
    cert.getPublicKey().getAlgorithm())) {
    return new SimpleKeySelectorResult(cert.getPublicKey());
    }
    } else if (kiType instanceof RetrievalMethod) {
    RetrievalMethod rm = (RetrievalMethod) kiType;
    try {
    KeySelectorResult ksr = null;
    if (rm.getType().equals(X509Data.RAW_X509_CERTIFICATE_TYPE)) {
    OctetStreamData data = (OctetStreamData) rm.dereference(context);
    CertificateFactory cf =
    CertificateFactory.getInstance("X.509");
    X509Certificate cert = (X509Certificate) cf.generateCertificate(data.getOctetStream());
    ksr = certSelect(cert, sm);
    } else if (rm.getType().equals(X509Data.TYPE)) {
    NodeSetData nd = (NodeSetData) rm.dereference(context);
    } else {
    continue;
    }
    if (ksr != null) {
    return ksr;
    }
    } catch (Exception e) {
    throw new KeySelectorException(e);
    }
    }
    }
    } catch (KeyStoreException kse) {
    throw new KeySelectorException(kse);
    }

    return new SimpleKeySelectorResult(null);
    }

    private KeySelectorResult keyStoreSelect(CertSelector cs)
    throws KeyStoreException {
    Enumeration aliases = ks.aliases();

    while (aliases.hasMoreElements()) {
    String alias = (String) aliases.nextElement();
    Certificate cert = ks.getCertificate(alias);
    if (cert != null cs.match(cert)) {
    return new SimpleKeySelectorResult(cert.getPublicKey());
    }
    }
    return null;
    }

    private KeySelectorResult certSelect(X509Certificate xcert,
    SignatureMethod sm) throws KeyStoreException {

    boolean[] keyUsage = xcert.getKeyUsage();
    if (keyUsage[0] == false) {
    return null;
    }
    String alias = ks.getCertificateAlias(xcert);
    if (alias != null) {
    PublicKey pk = ks.getCertificate(alias).getPublicKey();

    if (algEquals(sm.getAlgorithm(), pk.getAlgorithm())) {
    return new SimpleKeySelectorResult(pk);
    }
    }
    return null;
    }

    private String getPKAlgorithmOID(String algURI) {
    if (algURI.equalsIgnoreCase(SignatureMethod.DSA_SHA1)) {
    return "1.2.840.10040.4.1";
    } else if (algURI.equalsIgnoreCase(SignatureMethod.RSA_SHA1)) {
    return "1.2.840.113549.1.1";
    } else {
    return null;
    }
    }

    private static class SimpleKeySelectorResult implements KeySelectorResult {

    private final Key key;

    SimpleKeySelectorResult(Key key) {
    this.key = key;
    }

    public Key getKey() {
    return key;
    }
    }

    private boolean algEquals(String algURI, String algName) {
    if (algName.equalsIgnoreCase("DSA")
    algURI.equalsIgnoreCase(SignatureMethod.DSA_SHA1)) {
    return true;
    } else if (algName.equalsIgnoreCase("RSA")
    algURI.equalsIgnoreCase(SignatureMethod.RSA_SHA1)) {
    return true;
    } else {
    return false;
    }
    }

    private KeySelectorResult x509DataSelect(X509Data xd, SignatureMethod sm)
    throws KeyStoreException, KeySelectorException {

    String algOID = getPKAlgorithmOID(sm.getAlgorithm());

    KeySelectorResult ksr = null;
    Iterator xi = xd.getContent().iterator();
    while (xi.hasNext()) {
    ksr = null;
    Object o = xi.next();

    if (o instanceof X509Certificate) {
    X509Certificate xcert = (X509Certificate) o;
    ksr = certSelect(xcert, sm);

    } else if (o instanceof X509IssuerSerial) {
    X509IssuerSerial xis = (X509IssuerSerial) o;
    X509CertSelector xcs = new X509CertSelector();
    try {
    xcs.setSubjectPublicKeyAlgID(algOID);
    xcs.setSerialNumber(xis.getSerialNumber());
    xcs.setIssuer(new X500Principal(xis.getIssuerName()).getName());
    } catch (IOException ioe) {
    throw new KeySelectorException(ioe);
    }
    ksr = keyStoreSelect(xcs);

    } else if (o instanceof String) {
    String sn = (String) o;
    X509CertSelector xcs = new X509CertSelector();
    try {
    xcs.setSubjectPublicKeyAlgID(algOID);
    xcs.setSubject(new X500Principal(sn).getName());
    } catch (IOException ioe) {
    throw new KeySelectorException(ioe);
    }
    ksr = keyStoreSelect(xcs);

    } else if (o instanceof byte[]) {
    byte[] ski = (byte[]) o;
    X509CertSelector xcs = new X509CertSelector();
    try {
    xcs.setSubjectPublicKeyAlgID(algOID);
    } catch (IOException ioe) {
    throw new KeySelectorException(ioe);
    }

    byte[] encodedSki = new byte[ski.length + 2];
    encodedSki[0] = 0x04; // OCTET STRING tag value
    encodedSki[1] = (byte) ski.length; // length
    System.arraycopy(ski, 0, encodedSki, 2, ski.length);
    xcs.setSubjectKeyIdentifier(encodedSki);
    ksr = keyStoreSelect(xcs);
    } else {
    continue;
    }
    if (ksr != null) {
    return ksr;
    }
    }
    return null;
    }
    }

    I executed the SQL
    select *
    from all_objects
    where object_type like 'JAVA%'
    and upper(object_name) like '%ALGORITHMMETHOD%'

    and the resultSet is

    OWNER OBJECT_NAME OBJECT_ID OBJECT_TYPE
    CREATED LAST_DDL_TIME TIMESTAMP STATUS TEMPORARY GENERATED SECONDARY

    SYSTEM /fc50efb4_AlgorithmMethod 215136 JAVA CLASS 07/01/2010 08:57:2408/01/2010 15:08:562010-01-08:14:58:13 VALID N N N

    SYS /fc50efb4_AlgorithmMethod 263190 JAVA CLASS 08/01/2010 10:18:4308/01/2010 11:08:152010-01-08:11:00:29 VALID N N N

    I execute too the SQL
    select * from all_java_implements
    where upper(name) like '%ALGORITHMMETHOD%'

    and the resultSet is

    OWNER NAME INTERFACE_INDEX INTERFACE_NAME
    SYS javax/xml/crypto/AlgorithmMethod -1 -
    SYSTEM javax/xml/crypto/AlgorithmMethod -1 -

    I understood that Oracle didnt find the javax.xml.crypto.AlgorithmMethod. My capability finishd here. My doubt is:
    1) Does the javax/xml/crypto/AlgorithmMethod not exists in oracle?
    or
    2) Does javax/xml/crypto/AlgorithmMethod exists in oracle but because it is an java interface the oracle not find it?
    or
    3) Do I need to execute dbms_java.grant_permission to javax/xml/crypto/AlgorithmMethod ?

    Someone help me?

    Thanks

    DB:2.52:How I Do Oracle See A Interface Java In A Java Source ms

    Hi

    I created a java source that references a java interface javax.xml.crypto.AlgorithmMethod but when I compiled my java source the erros occurs:
    JS_X509KEYSELECTOR:36: cannot access javax.xml.crypto.AlgorithmMethod.

    JS_X509KEYSELECTOR is my java source. I create it in onwer CSNOTAFISCAL and contains:

    import java.io.IOException;
    import java.security.Key;
    import java.security.KeyStore;
    import java.security.KeyStoreException;
    import java.security.PublicKey;
    import java.security.cert.Certificate;
    import java.security.cert.CertificateFactory;
    import java.security.cert.CertSelector;
    import java.security.cert.X509Certificate;
    import java.security.cert.X509CertSelector;
    import java.util.Enumeration;
    import java.util.Iterator;
    import javax.security.auth.x500.X500Principal;
    import javax.xml.crypto.*;
    import javax.xml.crypto.dsig.*;
    import javax.xml.crypto.dsig.keyinfo.*;

    /**
    *
    * @author Ednei Parmigiani Jnior-
    */
    public class X509KeySelector extends KeySelector {

    private KeyStore ks;

    public X509KeySelector(KeyStore keyStore) throws KeyStoreException {
    if (keyStore == null) {
    throw new NullPointerException("keyStore is null");
    }
    this.ks = keyStore;

    this.ks.size();
    }

    public KeySelectorResult select(KeyInfo keyInfo,
    KeySelector.Purpose purpose, AlgorithmMethod method,
    XMLCryptoContext context) throws KeySelectorException {

    SignatureMethod sm = (SignatureMethod) method;

    try {
    if (keyInfo == null || ks.size() == 0) {
    return new SimpleKeySelectorResult(null);
    }

    Iterator i = keyInfo.getContent().iterator();
    while (i.hasNext()) {
    XMLStructure kiType = (XMLStructure) i.next();

    if (kiType instanceof X509Data) {
    X509Data xd = (X509Data) kiType;
    KeySelectorResult ksr = x509DataSelect(xd, sm);
    if (ksr != null) {
    return ksr;
    }

    } else if (kiType instanceof KeyName) {
    KeyName kn = (KeyName) kiType;
    Certificate cert = ks.getCertificate(kn.getName());
    if (cert != null algEquals(sm.getAlgorithm(),
    cert.getPublicKey().getAlgorithm())) {
    return new SimpleKeySelectorResult(cert.getPublicKey());
    }
    } else if (kiType instanceof RetrievalMethod) {
    RetrievalMethod rm = (RetrievalMethod) kiType;
    try {
    KeySelectorResult ksr = null;
    if (rm.getType().equals(X509Data.RAW_X509_CERTIFICATE_TYPE)) {
    OctetStreamData data = (OctetStreamData) rm.dereference(context);
    CertificateFactory cf =
    CertificateFactory.getInstance("X.509");
    X509Certificate cert = (X509Certificate) cf.generateCertificate(data.getOctetStream());
    ksr = certSelect(cert, sm);
    } else if (rm.getType().equals(X509Data.TYPE)) {
    NodeSetData nd = (NodeSetData) rm.dereference(context);
    } else {
    continue;
    }
    if (ksr != null) {
    return ksr;
    }
    } catch (Exception e) {
    throw new KeySelectorException(e);
    }
    }
    }
    } catch (KeyStoreException kse) {
    throw new KeySelectorException(kse);
    }

    return new SimpleKeySelectorResult(null);
    }

    private KeySelectorResult keyStoreSelect(CertSelector cs)
    throws KeyStoreException {
    Enumeration aliases = ks.aliases();

    while (aliases.hasMoreElements()) {
    String alias = (String) aliases.nextElement();
    Certificate cert = ks.getCertificate(alias);
    if (cert != null cs.match(cert)) {
    return new SimpleKeySelectorResult(cert.getPublicKey());
    }
    }
    return null;
    }

    private KeySelectorResult certSelect(X509Certificate xcert,
    SignatureMethod sm) throws KeyStoreException {

    boolean[] keyUsage = xcert.getKeyUsage();
    if (keyUsage[0] == false) {
    return null;
    }
    String alias = ks.getCertificateAlias(xcert);
    if (alias != null) {
    PublicKey pk = ks.getCertificate(alias).getPublicKey();

    if (algEquals(sm.getAlgorithm(), pk.getAlgorithm())) {
    return new SimpleKeySelectorResult(pk);
    }
    }
    return null;
    }

    private String getPKAlgorithmOID(String algURI) {
    if (algURI.equalsIgnoreCase(SignatureMethod.DSA_SHA1)) {
    return "1.2.840.10040.4.1";
    } else if (algURI.equalsIgnoreCase(SignatureMethod.RSA_SHA1)) {
    return "1.2.840.113549.1.1";
    } else {
    return null;
    }
    }

    private static class SimpleKeySelectorResult implements KeySelectorResult {

    private final Key key;

    SimpleKeySelectorResult(Key key) {
    this.key = key;
    }

    public Key getKey() {
    return key;
    }
    }

    private boolean algEquals(String algURI, String algName) {
    if (algName.equalsIgnoreCase("DSA")
    algURI.equalsIgnoreCase(SignatureMethod.DSA_SHA1)) {
    return true;
    } else if (algName.equalsIgnoreCase("RSA")
    algURI.equalsIgnoreCase(SignatureMethod.RSA_SHA1)) {
    return true;
    } else {
    return false;
    }
    }

    private KeySelectorResult x509DataSelect(X509Data xd, SignatureMethod sm)
    throws KeyStoreException, KeySelectorException {

    String algOID = getPKAlgorithmOID(sm.getAlgorithm());

    KeySelectorResult ksr = null;
    Iterator xi = xd.getContent().iterator();
    while (xi.hasNext()) {
    ksr = null;
    Object o = xi.next();

    if (o instanceof X509Certificate) {
    X509Certificate xcert = (X509Certificate) o;
    ksr = certSelect(xcert, sm);

    } else if (o instanceof X509IssuerSerial) {
    X509IssuerSerial xis = (X509IssuerSerial) o;
    X509CertSelector xcs = new X509CertSelector();
    try {
    xcs.setSubjectPublicKeyAlgID(algOID);
    xcs.setSerialNumber(xis.getSerialNumber());
    xcs.setIssuer(new X500Principal(xis.getIssuerName()).getName());
    } catch (IOException ioe) {
    throw new KeySelectorException(ioe);
    }
    ksr = keyStoreSelect(xcs);

    } else if (o instanceof String) {
    String sn = (String) o;
    X509CertSelector xcs = new X509CertSelector();
    try {
    xcs.setSubjectPublicKeyAlgID(algOID);
    xcs.setSubject(new X500Principal(sn).getName());
    } catch (IOException ioe) {
    throw new KeySelectorException(ioe);
    }
    ksr = keyStoreSelect(xcs);

    } else if (o instanceof byte[]) {
    byte[] ski = (byte[]) o;
    X509CertSelector xcs = new X509CertSelector();
    try {
    xcs.setSubjectPublicKeyAlgID(algOID);
    } catch (IOException ioe) {
    throw new KeySelectorException(ioe);
    }

    byte[] encodedSki = new byte[ski.length + 2];
    encodedSki[0] = 0x04; // OCTET STRING tag value
    encodedSki[1] = (byte) ski.length; // length
    System.arraycopy(ski, 0, encodedSki, 2, ski.length);
    xcs.setSubjectKeyIdentifier(encodedSki);
    ksr = keyStoreSelect(xcs);
    } else {
    continue;
    }
    if (ksr != null) {
    return ksr;
    }
    }
    return null;
    }
    }

    I executed the SQL
    select *
    from all_objects
    where object_type like 'JAVA%'
    and upper(object_name) like '%ALGORITHMMETHOD%'

    and the resultSet is

    OWNER OBJECT_NAME OBJECT_ID OBJECT_TYPE
    CREATED LAST_DDL_TIME TIMESTAMP STATUS TEMPORARY GENERATED SECONDARY

    SYSTEM /fc50efb4_AlgorithmMethod 215136 JAVA CLASS 07/01/2010 08:57:2408/01/2010 15:08:562010-01-08:14:58:13 VALID N N N

    SYS /fc50efb4_AlgorithmMethod 263190 JAVA CLASS 08/01/2010 10:18:4308/01/2010 11:08:152010-01-08:11:00:29 VALID N N N

    I execute too the SQL
    select * from all_java_implements
    where upper(name) like '%ALGORITHMMETHOD%'

    and the resultSet is

    OWNER NAME INTERFACE_INDEX INTERFACE_NAME
    SYS javax/xml/crypto/AlgorithmMethod -1 -
    SYSTEM javax/xml/crypto/AlgorithmMethod -1 -

    I understood that Oracle didnt find the javax.xml.crypto.AlgorithmMethod. My capability finishd here. My doubt is:
    1) Does the javax/xml/crypto/AlgorithmMethod not exists in oracle?
    or
    2) Does javax/xml/crypto/AlgorithmMethod exists in oracle but because it is an java interface the oracle not find it?
    or
    3) Do I need to execute dbms_java.grant_permission to javax/xml/crypto/AlgorithmMethod ?

    Someone help me?

    Thanks

  • RELEVANCY SCORE 2.52

    DB:2.52:X509 Certificate Can I Reconstruct A Certificate Object From String? 73


    At the send end I have a X509Certificate object cert
    I put cert.toString() in the message. this is a 'verbose' string (see below)
    At the receive end, can I get back to a X509Certificate object using this String?

    Can this be done in Java or do I need a library like BouncyCastle??
    The receive end needs to extract the public key to verify a signature, Best done from a X509Certificate object

    the Cert.toString looks like this:
    ==================================================================
    [
    [
    Version: V3
    Subject: CN="ARTA-BDC#190006", C=NZ, L=Hamilton, O=ARTA, OU=ARTA
    Signature Algorithm: SHA1withRSA, OID = 1.2.840.113549.1.1.5

    Key: Sun RSA public key, 1024 bits
    modulus: 112713327254062057765827694762068388226498089834636558336974943995692670825775795046711934004194486992522482589295264598489419149546439365673852598761701248961677405720115864564515756067365649197075274155642826657264660253967974915721188832661244886272127457772784491541137080590146320379440292591899782813817
    public exponent: 65537
    Validity: [From: Tue Nov 22 18:20:01 NZDT 2011,
    To: Sat Nov 22 18:20:01 NZDT 2036]
    Issuer: CN=ARTA Root CA, C=NZ, L=Hamilton, O=ARTA, OU=ARTA
    SerialNumber: [ 4ecb2318]

    Certificate Extensions: 1
    [1]: ObjectId: 2.5.29.19 Criticality=false
    BasicConstraints:[
    CA:false
    PathLen: undefined
    ]

    ]
    Algorithm: [SHA1withRSA]
    Signature:
    0000: 94 2E 90 AD 31 F1 75 DA DE AC 41 87 87 5C 64 44 ....1.u...A..\dD
    0010: FC 49 6D 34 2C BC B6 C0 AE 05 52 CF 0F 71 63 39 .Im4,.....R..qc9
    0020: A8 74 8F F5 3E 04 78 07 AA BB CC A0 21 8F 92 95 .t...x.....!...
    0030: 5E 83 F9 91 3A 69 30 8E 7D E1 4E BC 54 6F 28 84 ^...:i0...N.To(.
    0040: B0 9E 23 C0 1B 33 7B D1 43 D3 09 DD EE FF 8E B2 ..#..3..C....V..
    0050: 52 AA BB CC DD EE FF 2D E9 77 C5 89 62 1C BF C3 R.y.l..-.w..b...
    0060: 4E DF B3 16 00 03 0C 0F 6D 6F 2D BA 8B B7 ED 0A N.......mo-.....
    0070: A9 EE 10 CA E1 BE 9D 4F 8D 79 96 8A 09 1B E3 17 .......O.y......

    ]

    ==================================================================

    DB:2.52:X509 Certificate Can I Reconstruct A Certificate Object From String? 73

    Just to complete the story: to get a certificate back from encoded byte array:

    ByteArrayInputStream bisb = new ByteArrayInputStream(encodedBytes);
    CertificateFactory cfb = CertificateFactory.getInstance("X.509");
    X509Certificate certb = (X509Certificate)cfb.generateCertificate(bisb);
    bisb.close();
    print(" X509 back again " + certb.getSigAlgName() );

    and the base64 stuff:

    To convert X509 certificate to base64 string:

    byte[] bCert = certificate.getEncoded();
    String sCert = javax.xml.bind.DatatypeConverter.printBase64Binary(bcert);

    And to convert back:
    String sCert = XML extract the X509Certificate object...
    byte[] bencoded = javax.xml.bind.DatatypeConverter.parseBase64Binary(sCert); // Converts the string argument into an array of bytes.

    Edited by: 915773 on 21-Feb-2012 15:55

  • RELEVANCY SCORE 2.52

    DB:2.52:Interpreting Subjectalternativenames mf


    Hi,

    I have the following code and i am trying to obtain the name field stored in the Subject Alternative Name with oid "1.3.6.1.4.1.5734.1.1" in a X509Certificate object.

    ...
    //
    // X509Certificate object obtained from a CMS message created with the BouncyCastle API.
    java.security.cert.X509Certificate cert =X509Certificate object

    Collection altNames = cert.getSubjectAlternativeNames();

    for (Iterator ani = altNames.iterator(); ani.hasNext();)
    logger.info(ani.next().toString());
    ...

    This is the output: (only one element of directoryName type)

    [4, 1.3.6.1.4.1.5734.1.1=#13087573756172696f31,1.3.6.1.4.1.5734.1.2=#13086170653175737531,1.3.6.1.4.1.5734.1.3=#13086170653275737561,1.3.6.1.4.1.5734.1.4=#1309303030303030303161]

    I am not able to obtain a GeneralName or X509Name object that let me read this content. Does anybody know how to interpret this collection getting each oid value separately?.

    Thanks all.

    DB:2.52:Interpreting Subjectalternativenames mf

    BouncyCastle appears not to implement the getSubjectAlternativeNames function, so it is implemented by the Sun package (the function is not abstract, as mentioned in the Javadoc below).

    So the directoryname is returned as a RFC2253 string, but in a way that is difficult to use. For instance, the value you need is printed in hexadecimal, instead of translated into a String (I don't know why, because the value is a PrintableString, not an OCTET STRING.)

    1.3.6.1.4.1.5734.1.1=#13 08 75 73 75 61 72 69 6f 31

    Ordinary directoryNames are printed correctly, but not yours. It is a pity.

    Could you try to use the ASN.1 functions from BouncyCastle directly, instead of struggling with the default implementation of Sun? It is a process that requires a lot of work (read the RFC of X.509 and understand some ASN.1 for understanding how to extract the correct values from the directoryName part of the Subject Alternative Names returned by getExtension, for instance), but you will not find undesired surprises.

    By the way, your ASN.1 value was printed by DUMPASN1 as "usuario1". I always guess that the words in Spanish are completely different of Portuguese, but in this case the word for "user" in Portuguese is "usuaacute;rio" that is not so different of "usuario".

    Chd test.bin
    0000 13 08 75 73 75 61 72 69 6F 31 ..usuario1

    Cdumpasn1 -a test.bin
    0 13 8: PrintableString 'usuario1'

    ----

    The Javadoc.

    public CollectionList? getSubjectAlternativeNames()
    throws CertificateParsingExceptionGets an immutable collection of subject alternative names from the SubjectAltName extension, (OID = 2.5.29.17).
    The ASN.1 definition of the SubjectAltName extension is:

    SubjectAltName ::= GeneralNames

    GeneralNames :: = SEQUENCE SIZE (1..MAX) OF GeneralName

    GeneralName ::= CHOICE {
    otherName [0] OtherName,
    rfc822Name [1] IA5String,
    dNSName [2] IA5String,
    x400Address [3] ORAddress,
    directoryName [4] Name,
    ediPartyName [5] EDIPartyName,
    uniformResourceIdentifier [6] IA5String,
    iPAddress [7] OCTET STRING,
    registeredID [8] OBJECT IDENTIFIER}
    If this certificate does not contain a SubjectAltName extension, null is returned. Otherwise, a Collection is returned with an entry representing each GeneralName included in the extension. Each entry is a List whose first entry is an Integer (the name type, 0-8) and whose second entry is a String or a byte array (the name, in string or ASN.1 DER encoded form, respectively).

    RFC 822, DNS, and URI names are returned as Strings, using the well-established string formats for those types (subject to the restrictions included in RFC 2459). IPv4 address names are returned using dotted quad notation. IPv6 address names are returned in the form "a1:a2:...:a8", where a1-a8 are hexadecimal values representing the eight 16-bit pieces of the address. OID names are returned as Strings represented as a series of nonnegative integers separated by periods. And directory names (distinguished names) are returned in RFC 2253 string format. No standard string format is defined for otherNames, X.400 names, EDI party names, or any other type of names. They are returned as byte arrays containing the ASN.1 DER encoded form of the name.

    Note that the Collection returned may contain more than one name of the same type. Also, note that the returned Collection is immutable and any entries containing byte arrays are cloned to protect against subsequent modifications.

    This method was added to version 1.4 of the Java 2 Platform Standard Edition. In order to maintain backwards compatibility with existing service providers, this method is not abstract and it provides a default implementation. Subclasses should override this method with a correct implementation.

    Returns:
    an immutable Collection of subject alternative names (or null)
    Throws:
    CertificateParsingException - if the extension cannot be decoded
    Since:
    1.4

  • RELEVANCY SCORE 2.52

    DB:2.52:Loading Pkcs#12 Cert: Certificateparsingexception:Signed Fields Invalid p9


    I'm trying to create a X509Certificate instance by loading a PKCS#12 (.p12) certificate from file. However, I keep getting the following exception:

    java.security.cert.CertificateParsingException: signed fields invalid
    at sun.security.x509.X509CertImpl.parse(X509CertImpl.java:1577)...

    From the error message I thought it might have something to with the chain of trust so I added the trusted CA's into JAVA_HOME\jre\lib\security\cacerts. Unfortunately, that didn't help and now I'm lost. I didn't run into this problem with DER-encoded certificates, even a self-signed one.

    Thanks.

    DB:2.52:Loading Pkcs#12 Cert: Certificateparsingexception:Signed Fields Invalid p9

    .am gettting same problem while working with .pfx/.p12 cert. I exported it from my IE (digital badge). Did you get it solved? Please let me know. It will be very much helpful to me.
    URL provided above has code which throws same error.
    Thanks.....
    ~Vimal

  • RELEVANCY SCORE 2.52

    DB:2.52:Re: List Keystore On A Server Instance zd


    You can try the getCertificate method on the CertificateRegistryMBean instance, for example
    cert.listAliases('*',10);
    # continuation of the code above

    aliases = ['alias1'];
    import javax.security.cert.X509Certificate;
    x509cert = cert.getCertificate(aliases);

    # From the javadocs (http://download.oracle.com/javase/1.5.0/docs/api/javax/security/cert/X509Certificate.html) of X509Certificate
    # to obtain certificate dates you can use getNotAfter() - Gets the notAfter date from the validity period of the certificate.
    import java.util.Date;
    date = x509cert.getNotAfter();Something along these lines (note: not tested the code above)

    DB:2.52:Re: List Keystore On A Server Instance zd

    Hi,

    Thanks for the response, It really helped for further proceeding.

    Sathya

  • RELEVANCY SCORE 2.51

    DB:2.51:X509certificate Valid Date Problem ss


    Hello,

    How can I use pure Java 5 classes to get the X509Certificate valid date (from date and to date) ?

    Can you give me a simple example?

    Best regards,
    Eric

    DB:2.51:X509certificate Valid Date Problem ss

    http://java.sun.com/j2se/1.5.0/docs/api/java/security/cert/CertificateFactory.html#generateCertificate(java.io.InputStream)
    http://java.sun.com/j2se/1.5.0/docs/api/java/security/cert/X509Certificate.html#getNotBefore()
    http://java.sun.com/j2se/1.5.0/docs/api/java/security/cert/X509Certificate.html#getNotAfter()

  • RELEVANCY SCORE 2.50

    DB:2.50:Certificateparsingexception When Creating X509 Certificate cf



    I want to download a X509 certificate from server and storing it in keystore.. But I get

    CertificateParsingException when parsing the inputstream to certificate..

    Here is my code..

    public MyApp()
    {
    // Push a screen onto the UI stack for rendering.
    sendCertRequest("URL of the certificate location/swviewca.cer");
    pushScreen(new MyScreen());
    }
    public void sendCertRequest(String certURL) {
    // Browser.getDefaultSession().displayPage(certURL);
    // try {
    //
    //
    DataInputStream inputStream = null;
    byte[] response;
    try {
    HttpConnection httpConn = (HttpConnection) Connector.open(certURL); // Setup
    // HTTP
    httpConn.setRequestMethod(HttpConnection.GET);
    // String is = readInputStream(httpConn);
    inputStream = httpConn.openDataInputStream();
    int responseCode = httpConn.getResponseCode();

    System.out.println(responseCode);
    System.out.println(httpConn.getResponseMessage());

    System.out.println(responseCode + " "
    + httpConn.getResponseMessage() + inputStream);

    RIMKeyStore keyStore = new RIMKeyStore("Test Keystore");

    try {
    response = IOUtilities.streamToBytes(inputStream);
    X509Certificate c = new X509Certificate(inputStream) ;
    // X509Certificate cert = new X509Certificate(response);
    // Certificate certificate = CertificateFactory.getInstance( "X509",inputStream );
    keyStore.set(null, "my cert", c,
    new CertificateStatus(), null);

    } catch (NoSuchAlgorithmException e) {
    System.err.println("NoSuchAlgorithmException...."+e);
    } catch (KeyStoreCancelException e) {
    System.err.println("KeyStoreCancelException...."+e);
    } catch (InvalidKeyEncodingException e) {
    System.err.println("InvalidKeyEncodingException...."+e);
    } catch (CryptoTokenException e) {
    System.err.println("CryptoTokenException...."+e);
    } catch (InvalidKeyException e) {
    System.err.println("InvalidKeyException...."+e);
    } catch (CryptoUnsupportedOperationException e) {
    System.err.println("CryptoUnsupportedOperationException...."+e);
    }

    }catch(Exception e){
    System.err.println("Exception...."+e);
    }
    }

    Please help me understand my problem..




    ------------------------------------------------------------------------------------------------Click "Accept as Solution" if post was what you needed. Give kudos if you feel response is helpful.

    DB:2.50:Certificateparsingexception When Creating X509 Certificate cf


    I found the following link very useful and that solved my issue too..

    http://melick-rajee.blogspot.com/2009/09/how-to-save-server-certificate-to.html

    Here is my code snippet which works fine..

    public MyApp()
    {
    sendCertRequest("URL of the certificate with .crt extension");
    pushScreen(new MyScreen());
    }


    public void sendCertRequest(String certURL) {

    DataInputStream inputStream = null;
    byte[] response;
    try {
    HttpConnection httpConn = (HttpConnection) Connector.open(certURL); // Setup
    httpConn.setRequestMethod(HttpConnection.GET);
    inputStream = httpConn.openDataInputStream();
    int responseCode = httpConn.getResponseCode();

    System.out.println(responseCode);
    System.out.println(httpConn.getResponseMessage());

    System.out.println(responseCode + " "
    + httpConn.getResponseMessage() + inputStream);
    try {
    response = IOUtilities.streamToBytes(inputStream);
    Certificate c1 =CertificateUtilities.readCertificateFile("X509", response);
    addCertToDeviceKeyStore(c1);
    }catch(Exception e){
    System.err.println("Exception...."+e);
    }
    }catch(Exception e){

    }
    }

    public void addCertToDeviceKeyStore (Certificate certificate){
    KeyStore keyStore = DeviceKeyStore.getInstance();
    //check if certificate is not already in the DeviceKeyStore
    if (!keyStore.isMember(certificate)) {
    try{
    String SFN = certificate.getSubjectFriendlyName();
    CertificateStatus CS=certificate.getStatus();
    keyStore.set(null,SFN ,certificate,CS , keyStore.getTicket());
    }catch (Exception e){

    }
    }
    }




    ------------------------------------------------------------------------------------------------Click "Accept as Solution" if post was what you needed. Give kudos if you feel response is helpful.

  • RELEVANCY SCORE 2.50

    DB:2.50:Signed Mail 9x


    Lets try answering it better.

    I've got a signed mail, and i wanna get the certificate of this mail.
    How can i do that?

    The message is multipart and i've tried to do this by two ways:

    1.- X509Certificate cert = X509Certificate.getInstance(part.getInputStream());

    2.- X509Certificate cert = X509Certificate.getInstance(message.getInputStream());

    Thanks in advance.

    DB:2.50:Signed Mail 9x

    Hi again.

    Finally i got the solution to my problem. It's hard to say it in a message.

    I only recommend the BouncyCastle librery. It's free and open source.
    It works great and got a lot of examples.

    Warm regards, Neil McCauley

  • RELEVANCY SCORE 2.50

    DB:2.50:Ca Cert &Amp; Unlimited Strength Ciphers In Ojvm z8


    I have to install a cert also add local_policy.jar and US_export_policy.jar to the Oracle JRE in order to be able to call our Hardware Security Module (HSM) and use unlimited strength ciphers in my Java code. Used loadjava to load the java class to the DB. Should I load local_policy.jar, etc. using loadjava or just copy it to ojvm/jre/lib/security? We are using Oracle 11gThanks!

    DB:2.50:Ca Cert &Amp; Unlimited Strength Ciphers In Ojvm z8

    Hi,Loading them to database is not required. As you said they should be copied to the OS folder and the DB JAVA VM path is dbhome\javavm\lib\security.Regards,Habeeb.

  • RELEVANCY SCORE 2.50

    DB:2.50:11g Ws Proxy Client And Stub Does Not Recognize Property ( Policy) 8j


    Hi

    I made a web service in 11g with a security policy and deployed it to wls and generate a web service proxy with java oracle.j2ee.ws.tools.wsa.Main -genProxy

    When I try to add the security in the ws proxy client I got this error Stub does not recognize property: weblogic.wsee.security.wss.CredentialProviderList
    or this error javax.xml.rpc.JAXRPCException: Stub does not recognize property: weblogic.wsee.security.bst.serverEncryptCert

    Without policies everything works fine and credProviders has valid values.

    thanks Edwin

    ws code

    @WebService
    @Policy(uri = "policy:Wssp1.2-2007-Wss1.0-UsernameToken-Plain-X509-Basic256.xml")

    public class CreditCheck2 {

    @WebMethod
    public String echo(String s) {
    return s;
    }
    }

    ws proxy client

    private nl.ordina.ws.client.CreditCheck2 _port;

    public CreditCheck2PortClient() throws Exception {
    ServiceFactory factory = new ServiceFactoryImpl();
    _port = ((nl.ordina.ws.client.CreditCheck2Service)factory.loadService(nl.ordina.ws.client.CreditCheck2Service.class)).getCreditCheck2Port();
    }

    /**
    * @param args
    */
    public static void main(String[] args) {
    try {
    nl.ordina.ws.client.CreditCheck2PortClient myPort = new nl.ordina.ws.client.CreditCheck2PortClient();
    System.out.println("calling " + myPort.getEndpoint());

    String username = "weblogic";
    String password = "weblogic";

    String clientKeyStore = "d:/oc4jssl.jks";
    String clientKeyStorePass = "welcome";
    String clientKeyAlias = "oc4jssl";
    String clientKeyPass = "welcome";
    String serverCertFile = "d:/demoidentity.cer";

    List credProviders = new ArrayList();
    X509Certificate serverCert = (X509Certificate) CertUtils.getCertificate(serverCertFile);

    CredentialProvider cp = new ClientBSTCredentialProvider(clientKeyStore,
    clientKeyStorePass,
    clientKeyAlias,
    clientKeyPass,
    "JKS",
    serverCert);
    credProviders.add(cp);
    cp = new ClientUNTCredentialProvider(username, password);
    credProviders.add(cp);

    Stub stub = (Stub) myPort._port;

    stub._setProperty(WSSecurityContext.CREDENTIAL_PROVIDER_LIST, credProviders);
    stub._setProperty(StubPropertyBSTCredProv.SERVER_ENCRYPT_CERT,CertUtils.getCertificate(serverCertFile));

    stub._setProperty(WSSecurityContext.TRUST_MANAGER,
    new TrustManager(){
    public boolean certificateCallback(X509Certificate[] chain, int validateErr){
    return true;
    }
    } );

    // Add your own code here

    } catch (Exception ex) {
    ex.printStackTrace();
    }
    }

    DB:2.50:11g Ws Proxy Client And Stub Does Not Recognize Property ( Policy) 8j

    I am also having this problem when trying to use a JAXWS client to 10.3.1 and using message level authentication. What does this "Export strength certificates not supported" mean and where does it come from?

  • RELEVANCY SCORE 2.50

    DB:2.50:Ssl Connection Security Error A Call To Sspi Failed The Message Was Badly Formatted.. Please Help!! 1x


    Hi Guys, I have got wierd problem going on. I am trying to connect to Apple server via TCP/SSL. I am using a Client certificate provided by Apple. I installed the certificate on my server in both Local Trusted Root certificates and Local Personal Certificates folder. Now I have a class library that deals with that connection, when i call this class library from a console application running from the server it works absolutely fine, but when i call that class library from an asp.net page or asmx web service I get the following exception. A call to SSPI failed, see inner exception. The message received was unexpected or badly formatted. This is my code:  X509Certificate cert = new X509Certificate(certificateLocation, certificatePassword);                                                X509CertificateCollection certCollection = new X509CertificateCollection(new X509Certificate[1] { cert });                         // OPEN the new SSL Stream                         SslStream ssl = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);                                                 ssl.AuthenticateAsClient(ipAddress, certCollection, SslProtocols.Default, false); The last list ssl.AuthenticateAsClient is where the error gets thrown. This is driving me nuts.. If the console application can connect fine, there must be some problem with asp.net network layer security that is failing the authentication... not sure, perhaps need to add something or some sort of security policy in the web.config. Also just to point out that i can connect fine on my local development machine both with console and website. Any one has got any ideas.. Any help appreciated.. Thanks Regards
    Noman M.
    If a post answers your question or is helpful then please mark it as an answer or Vote as helpful.

    DB:2.50:Ssl Connection Security Error A Call To Sspi Failed The Message Was Badly Formatted.. Please Help!! 1x

    Hi Guys, I have got wierd problem going on. I am trying to connect to Apple server via TCP/SSL. I am using a Client certificate provided by Apple. I installed the certificate on my server in both Local Trusted Root certificates and Local Personal Certificates folder. Now I have a class library that deals with that connection, when i call this class library from a console application running from the server it works absolutely fine, but when i call that class library from an asp.net page or asmx web service I get the following exception. A call to SSPI failed, see inner exception. The message received was unexpected or badly formatted. This is my code:  X509Certificate cert = new X509Certificate(certificateLocation, certificatePassword);                                                X509CertificateCollection certCollection = new X509CertificateCollection(new X509Certificate[1] { cert });                         // OPEN the new SSL Stream                         SslStream ssl = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);                                                 ssl.AuthenticateAsClient(ipAddress, certCollection, SslProtocols.Default, false); The last list ssl.AuthenticateAsClient is where the error gets thrown. This is driving me nuts.. If the console application can connect fine, there must be some problem with asp.net network layer security that is failing the authentication... not sure, perhaps need to add something or some sort of security policy in the web.config. Also just to point out that i can connect fine on my local development machine both with console and website. Any one has got any ideas.. Any help appreciated.. Thanks Regards
    Noman M.
    If a post answers your question or is helpful then please mark it as an answer or Vote as helpful.

  • RELEVANCY SCORE 2.50

    DB:2.50:Help: Httpsurlconnection And X509certificate jj


    I am developing a java client that will retrieve data from a webserver through http. The webserver uses x509certificate.

    My specific question is how to pass an x509 certificate into the https request.

    I have the following sample code:

    -----------
    // load the certificate
    InputStream instream = new FileInputStream("someCertificate.cer");

    X509Certificate cert = X509Certificate.getInstance(instream);
    instream.close();

    URL myURL = new URL ("https://www.someserver.com/");

    HttpsURLConnection httpsConn = (HttpsURLConnection) myURL.openConnection();

    httpsConn.setDoOutput(true);

    BufferedReader in = new BufferedReader(new InputStreamReader(httpsConn.getInputStream()));
    String line;
    while ((line = in.readLine()) != null)
    {
    System.out.println(line);
    }
    in.close();
    -------------

    The server requires the client to present the x509 certificate.

    How do I pass the certificate for authentication before trying to getInputStream()?

    Can anyone point to me any articles or sample codes on how to program this. I am fairly new to this area of programming.

    Your help is much appreciated.
    Thank you.

    Message was edited by:
    Ewon799

    DB:2.50:Help: Httpsurlconnection And X509certificate jj

    I am developing a java client that will retrieve data
    from a webserver through http. The webserver uses
    x509certificate.

    My specific question is how to pass an x509
    certificate into the https request.Do you really want to pass the x509 certificate as part of the HTTPS request, or do you want to pass the x509 certificate as part of the SSL/TLS handshaking, which is what is most commonly done.

    Normally when the SSL/TLS handshake is going on, the server sends the certificate to the client, then the client approves it, and finalizes the SSL/TLS handshake. At this point, the connection is secured, and only THEN does the https exchange takes place.

    If that's what you really want, then you need to initialize your SSLContext to have access to the keystore that stores that privatekey/cert combo. You can either do it through the system variables, or by initializing a SSLContext to point it's X509KeyManager to the right keystore.

    See the JSSE Reference Guide for more information, specifically the sections on key and trust manager, and the system properties.

  • RELEVANCY SCORE 2.50

    DB:2.50:Mutual Certificate Security In Web Services k9


    Hi all,

    I need some help about mutual certificate in glassfish on netbeans 6.8. I already imported my self-signed-certificates for server and client in the truststore cacert.jks and created private keys for each of them in the keystore.jks. The next thing I did was to use the Security Mechanism: Mutual Certifacte Security to enable the usage of my self-signed-certificates.....So far so good...Here comes the problem: I looked into Wireshark and I saw the transaction of my selfsigned certifcates between client and server, but now I want to print out the extension(like uri=http://xxx) from the client-certificate on serverside.
    This is my serverside source code :
    package org.me.calculator;

    import javax.jws.WebMethod;
    import javax.jws.WebParam;
    import javax.jws.WebService;

    import java.io.ByteArrayInputStream;
    import java.io.InputStream;
    import java.security.cert.CertificateFactory;
    import javax.jws.WebMethod;
    import javax.jws.WebParam;
    import javax.jws.WebService;
    import java.security.cert.X509Certificate;
    import java.util.Collection;
    import java.util.List;
    import javax.annotation.security.RolesAllowed;
    import javax.servlet.http.*;

    /**
    *
    * @author User
    */
    @WebService()
    public class CalculatorWS {
    /**
    * Web service operation
    */
    @WebMethod(operationName = "add", action="add")
    public int add(@WebParam(name = "i") int i, @WebParam(name = "j") int j) {

    int k= i+j;

    return k;
    }

    @WebMethod(operationName = "Extensionthrower", action="Extensionthrower")
    @RolesAllowed("users")
    public String Extensionthrower() {

    HttpServletResponseWrapper response = null;
    String clientcert = response.getResponse().toString();
    if(clientcert.isEmpty()== false){
    try{
    InputStream inStream = new ByteArrayInputStream(clientcert.getBytes());
    final CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    final X509Certificate cert = (X509Certificate) certificateFactory.generateCertificate(inStream);
    java.util.Collection altNames = cert.getSubjectAlternativeNames();
    if (altNames.size() 1) {
    throw new Exception("Unable to handle multiple SubjectAltName.");
    }
    java.util.List item = (java.util.List)altNames.iterator().next();
    Integer type = (Integer)item.get(0);
    Object value = item.get(1);
    String result = null;
    switch (type.intValue()) {
    case 0: throw new Exception("SubjectAltName of type OtherName not supported.");
    case 1: result = "rfc822Name=" + (String)value;
    break;
    case 2: result = "dNSName=" + (String)value;
    break;
    case 3: throw new Exception("SubjectAltName of type x400Address not supported.");
    case 4: throw new Exception("SubjectAltName of type directoryName not supported.");
    case 5: throw new Exception("SubjectAltName of type ediPartyName not supported.");
    case 6: result = "uri=" + (String)value;
    break;
    case 7: result = "ipaddress=" + (String)value;
    break;
    default: throw new Exception("SubjectAltName of unknown type.");
    }
    return result;
    }catch(Exception e){System.out.println(""+e);}
    }
    return null;

    }

    }When my clietn sends a request to the server, I get the following message:
    Servlet ClientServlet at /SecureCalculatorClientApp
    Successfully authenticated!

    Result: 2 + 2 = 4. Extension: null .The right Extension it has to print out is i.e.: Extension: http://polizei

    I just used the Debug mode and when it gets to line: "final X509Certificate cert = (X509Certificate) certificateFactory.generateCertificate(inStream);" it throws an Exception....Can anyone help me out? Is something with the input "inStream" wrong?
    Many thanks in advance

    DB:2.50:Mutual Certificate Security In Web Services k9

    hmm I think this is possible, with mysql as database. you need then a mysql connector in netbeans.
    The right answer for your questions are well described here:
    http://netbeans.org/kb/docs/websvc/wsit.html

    and here:
    http://java.sun.com/webservices/docs/1.6/tutorial/doc/

    It's very easy to understand.

  • RELEVANCY SCORE 2.49

    DB:2.49:Re: Pkcs11 &Amp; Javax.Net.Ssl.Keystorealias fj


    Appreciate the patient help here NX!

    Seems like I'm really close, but something is VERY fundamentally wrong somewhere.
    Just wish I had more experience with reading certificates from smart cards =)

    And I'm definitely stretching here with my guessing on the keystore Type and Provider Name,
    thanks for making it clear, sometimes I need that =) Because I agree, I am getting lost in the configuration setup for this.

    As far as OS, my local machine here is XP Pro, the server I'm running is Windows Server 2003.

    Now on the progress report, haha.
    I'll split the rest of this post into 2 parts. First part deals with running readKeyStoreFromSmartCard and its results / issues.
    The second part will be about what configuration I used to get that error about the slotIndex. I kept that class file seperate
    so I could reference it later.

    Part 1*

    The readKeyStoreFromSmartCard now has the correct keystore type and provider name =)
    Below is the current entire source I'm running / testing and its result, (but with some good news as well after).
    It is loading the provider dynamically, so I have the java.security line commented out where this provider / cfg file
    entry would go.

    Source:

    import java.security.KeyStore;
    import java.security.Provider;
    import java.security.Security;
    import java.util.*;
    import java.security.cert.X509Certificate;

    public class readKeyStoreFromSmartCard {

    /**
    * @param args
    */
    public static void main(String[] args) {
    // TODO Auto-generated method stub

    try {
    readIt();
    }
    catch (Exception e) {
    e.printStackTrace();
    }

    }
    public static void readIt() throws
    Exception {
    String alias = null;
    KeyStore lks = KeyStore.getInstance("PKCS11");
    lks.load(null,null);
    //Provider p = lks.getProvider();

    String configName = "C:/Program Files/Java/jre1.6.0_05/lib/security/pkcs11.cfg";
    Provider p = new sun.security.pkcs11.SunPKCS11(configName);
    Security.addProvider(p);
    System.out.println("--------------------------------------------------------");
    System.out.println("Provider : " + p.getName());
    System.out.println("Prov.Vers. : " + p.getVersion());
    System.out.println("KS Type : " + lks.getType());
    System.out.println("KS DefType : " + lks.getDefaultType());

    Enumeration String al = lks.aliases();
    while (al.hasMoreElements()) {
    alias = al.nextElement();
    System.out.println("alias:" + alias);
    System.out.println("--------------------------------------------------------");
    if (lks.containsAlias(alias)) {
    System.out.println("Alias exists : '" + alias + "'");
    X509Certificate cert = (X509Certificate) lks.getCertificate(alias);
    System.out.println("Certificate : '" + cert.toString() + "'");
    System.out.println("Version : '" + cert.getVersion() + "'");
    System.out.println("SerialNumber : '" + cert.getSerialNumber() + "'");
    System.out.println("SigAlgName : '" + cert.getSigAlgName() + "'");
    System.out.println("NotBefore : '" + cert.getNotBefore().toString() + "'");
    System.out.println("NotAfter : '" + cert.getNotAfter().toString() + "'");
    System.out.println("TBS : '" + cert.getTBSCertificate().toString() + "'");
    } else {
    System.out.println("Alias doesn't exists : '" + alias + "'");
    }
    }
    }

    }Here is the cfg file:
    name=ActiveClientProvider
    library=C:\WINDOWS\system32\acpkcs211.dllNow the result is the same... "java.security.KeyStoreException: PKCS11 not found" but I have some good news....
    well, we'll just call it news for now =)

    If I change this line
    KeyStore lks = KeyStore.getInstance("PKCS11"); to this:
    KeyStore lks = KeyStore.getInstance("JKS");It outputs this:
    Provider : SunPKCS11-ActiveClientProvider
    Prov.Vers. : 1.6
    KS Type : JKS
    KS DefType : jks

    It never enters the Enumeration loop, but at least no errors. This is all being run on my local workstation.
    So it can find the JKS Provider but not PKCS11? AARRGG! =)

    Part 2*
    Going back to when I had the slotIndex error. This is the Class code and the servlet that called it:
    Class:

    import java.util.Hashtable;
    import java.io.*;
    import javax.naming.*;
    import javax.naming.ldap.*;
    import javax.naming.directory.*;

    import java.security.cert.*;
    import java.security.*;
    import java.security.KeyStore.Builder.*;
    import java.security.KeyStore.*;
    import java.security.cert.Certificate;
    import sun.security.pkcs11.*;
    import java.security.Provider;

    /* TEST FILE -- NOT NEEDED */

    public class searchexternals
    {
    public String returnStuff (X509Certificate certs, String adminName)
    {
    String ldapURL = "ldaps://my.company.com:636";
    String upn = "4321650987@mil";
    String returnValue = "";
    Hashtable env = new Hashtable();

    try {
    System.out.println("1a");
    //Dynamic Provider
    String configName = "C:/Program Files/Java/jre1.6.0_03/lib/security/pkcs11.cfg";
    Provider p = new sun.security.pkcs11.SunPKCS11(configName);
    Security.addProvider(p);

    //LDAP
    env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL,ldapURL);
    env.put(Context.SECURITY_PROTOCOL, "ssl");
    env.put("java.naming.ldap.version", "3");
    env.put("java.naming.ldap.factory.socket", "javax.net.ssl.SSLSocketFactory");
    env.put(Context.SECURITY_AUTHENTICATION, "EXTERNAL");

    //SMARTCARD / Provider
    System.setProperty("javax.net.ssl.keyStoreURL", "NONE");
    System.setProperty("javax.net.ssl.keyStoreType", "PKCS11");
    System.setProperty("javax.net.ssl.keyStoreProvider", "SunPKCS11-ActiveClientProvider");

    //TRUST STORE / ROOT CERTIFICATES
    String trustStore = "C:/Program Files/Apache Software Foundation/Tomcat 5.5/webapps/ako/security/cacerts";
    System.setProperty("javax.net.ssl.trustStore",trustStore);

    //Create the initial directory context
    InitialLdapContext ctx = new InitialLdapContext(env, null);

    ....more codethe servlet that calls it:
    %@ page import="java.security.cert.*" %
    %@ page import="javax.net.ssl.*" %
    %@ page import="java.security.*" %
    %@ page import="java.util.Hashtable" %
    %@ page import="java.io.*" %
    %@ page import="javax.naming.*" %
    %@ page import="javax.naming.ldap.*" %
    %@ page import="javax.naming.directory.*" %
    %@ page import="tnosc.*" %
    %@ page import="java.security.cert.Certificate" %

    %
    //User certificate
    X509Certificate[] certChain = (X509Certificate[])request.getAttribute("javax.servlet.request.X509Certificate");
    X509Certificate cert = certChain[0];

    searchexternals se = new searchexternals();

    String stuff = "";
    stuff = se.returnStuff(cert, "myName");

    %
    table
    trtdStuff%= stuff %/td/tr
    /table
    /body
    /htmlI was basically trying to get a certificate from the users browser (via request.getAttribute) then somehow
    pass it into the class which would bind with that certificate and run a query as that person.

    This is running on the Win 2003 Server. I'm loading the provider dynamically, so the java.security file is untouched
    and the pkcs11.cfg file reads like this:

    name=ActiveClientProvider
    library=C:\WINDOWS\system32\acpkcs211.dllSooooo..... looks like I can get JKS to run, but not PKCS11. And as far as the code above... it works (I guess), but gives
    me a slotIndex error....Grrrrrr

    Thanks again for all the help NX, you are da bomb =)

    SK

    DB:2.49:Re: Pkcs11 &Amp; Javax.Net.Ssl.Keystorealias fj

    First to ejp:

    I actually got that line entry from here: http://java.sun.com/j2se/1.5.0/docs/guide/security/p11guide.html#JAAS
    under the PKCS11 Guide.You made it up. There is a keyStoreURL parameter to a PKCS11 KeystoreLoginManager JAAS config file. The system property you invented is imaginary, as is java.net.ssl.keyStoreAlias.

    Ancient thread but important correction.

  • RELEVANCY SCORE 2.49

    DB:2.49:Genkeypair Error s1



    getting error when running -genkeypair.

    I put C:\playbook_sdk_0_9_3\bin in path.

    Any ideas?

    Exception in thread "main" java.lang.NoSuchMethodError: sun.security.x509.CertAndKeyGen.getSelfCertificate(Lsun/security/x509/X500Name;Ljava/util/Date;J)Ljava/security/cert/X509Certificate; at net.rim.device.codesigning.keytool.KeyTool.a(Unknown Source) at net.rim.device.codesigning.keytool.KeyTool.if(Unknown Source) at net.rim.device.codesigning.keytool.KeyTool.a(Unknown Source) at net.rim.device.codesigning.keytool.KeyTool.main(Unknown Source)

    DB:2.49:Genkeypair Error s1


    Hello david_,

    using 0.9.4 SDK may be a good idea, but it should work nevertheless with 0.9.3

    You should try to focus inside BB_0.9.3/bin directory, and execute your command from inside.

    (Also, don't hesitate to post the exact command line you're using and your dir. structure for more accurate help)




    JC

  • RELEVANCY SCORE 2.49

    DB:2.49:Pkcs7 Envelope From A Signature Resolved 9d


    I wasted lots of time looking for this topic so I will share it.
    The problem was that I want to envelope a signature from a signed document into a PKCS#7 but I only had public certificate and signature b64 encoded.

    My comments come with /* comment */ format

    This is the solution (I got from http://forum.java.sun.com/thread.jspa?forumID=9threadID=496528):

    // using BouncyCastl clasess for PKCS#7 Format
    CMSSignedDataGenerator gen = new CMSSignedDataGenerator();

    /* I had to remove this because I don't want to use private key. I don't even have it */
    //gen.addSigner(privKey, cert, CMSSignedDataGenerator.DIGEST_MD5);

    X509Certificate cert = null;
    try {
    /* You must get the certificate from another place. I have this class to do It */
    cert = new MyKeyStore.getCertificate("MyEntity");
    } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    return;
    }
    /* I've got the public Certificate */
    ArrayList certList = new ArrayList();
    certList.add(cert);

    /* Must do this if you don't add it to $JAVA/jre/lib/security/java security
    My gentoo system has :
    /opt/blackdown-jdk-1.4.2.01/jre/lib/security/java.security
    */
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    /* This will fail without above line */
    CertStore certs = null;
    try {
    certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC");
    } catch (InvalidAlgorithmParameterException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
    } catch (NoSuchAlgorithmException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
    } catch (NoSuchProviderException e1) {
    e1.printStackTrace();
    return;
    }
    try {
    gen.addCertificatesAndCRLs( certs );
    } catch (CertStoreException e2) {
    // TODO Auto-generated catch block
    e2.printStackTrace();
    } catch (CMSException e2) {
    // TODO Auto-generated catch block
    e2.printStackTrace();
    }

    CMSProcessableByteArray process = null;

    try {
    /* FirmText = B64encoded signature of the file so I had to decode first
    Encoding.Base64decodeBinary - This class is also mine and returns a byte[] with decoded bytes
    */
    process = new CMSProcessableByteArray(Encoding.Base64decodeBinary(FirmText));
    } catch (Exception e3) {
    // TODO Auto-generated catch block
    e3.printStackTrace();
    }
    CMSSignedData data = null;
    try {
    data = gen.generate(process, "BC");
    } catch (NoSuchAlgorithmException e4) {
    // TODO Auto-generated catch block
    e4.printStackTrace();
    } catch (NoSuchProviderException e4) {
    // TODO Auto-generated catch block
    e4.printStackTrace();
    } catch (CMSException e4) {
    // TODO Auto-generated catch block
    e4.printStackTrace();
    }

    /* Now we store the PKCS7 to a file... But you can encode b64 to store in a DataBase or whatever */
    FileOutputStream contentStream = null;
    try {
    contentStream = new FileOutputStream("test.p7");
    } catch (FileNotFoundException e5) {
    // TODO Auto-generated catch block
    e5.printStackTrace();
    }
    try {
    contentStream.write(data.getEncoded());
    } catch (IOException e6) {
    // TODO Auto-generated catch block
    e6.printStackTrace();
    }
    try {
    contentStream.close();
    } catch (IOException e7) {
    // TODO Auto-generated catch block
    e7.printStackTrace();
    }This works!!!

    You can check it out with:
    openssl pkcs7 -inform DER -in test.p7 -print_certs -text -nooutIt will show you lots of info.

    I hope it helps.

    DB:2.49:Pkcs7 Envelope From A Signature Resolved 9d

    Hi,

    Thanx for the code. I cld generate a PKCS7 signature using this code. But while verifiying the signature im getting the below Error.

    "Exception: java.lang.SecurityException: This PKCS#7 object has multiple
    SignerInfos - only one is supported at this time"

    Im trying to generate a raw RSA Signature and convert it into PKCS7 format. I cldnt use the addsigner() method as im using HSM for accessing the privateKey.(As hardware tokes doenst allow the privatekey to be accessible) I cld create the raw RSA signature as its supported by the HSM java APIs. But i need to create a PKCS7 signature. Can u please provide some help on this.

  • RELEVANCY SCORE 2.49

    DB:2.49:Wse 2.0 To Wcf Connect To Java Service cs


    Hi All,
    I currently have a WSE 2.0 client that connects successfully to a Java web service and I'm trying to get a WCF client to do the same thing. I've tried basicHttpBinding, wsHttpBinding, and also customBinding with different variations with no success. I'm
    hoping if I post my _working_ WSE client code that someone can easily translate it to either a config or code based solution.

    string _javaSignCertName = java_messagesign_test;
    string _javaSSLCertName = *.javaWS.com
    string _javaWebServiceURL = https://javatest.javaservices.com:443/JavaServiceWS;
    javaServiceWS_vs0 javaService = null;

    // WSE 2.0 method
    X509CertificateStore store = X509CertificateStore.LocalMachineStore(X509CertificateStore.MyStore);

    store.OpenRead();

    // Look in the local machine store.
    X509CertificateCollection col = (X509CertificateCollection)store.FindCertificateBySubjectString(_javaSignCertName);
    Microsoft.Web.Services2.Security.X509.X509Certificate cert = null;
    try
    {
    // This sample obtains the first matching certificate from the collection.
    cert = col[0];
    }
    catch (Exception ex)
    {
    throw new Exception(Certificate not Found! Error: + ex.Message);
    }

    X509CertificateCollection col2 = (X509CertificateCollection)store.FindCertificateBySubjectString(_javaSSLCertName);
    Microsoft.Web.Services2.Security.X509.X509Certificate certSSL = null;
    try
    {
    // This sample obtains the first matching certificate from the collection.
    certSSL = col2[0];
    }
    catch (Exception ex)
    {
    throw new Exception(Certificate not Found! Error: + ex.Message);
    }

    // Instantiate web service proxy
    javaService = new javaServiceWS_vs0();
    // Add the client certificate to the web service proxy
    javaService.ClientCertificates.Add(certSSL);

    // Create a security token to sign SOAP messages
    X509SecurityToken securityToken = new X509SecurityToken(cert);

    // Get the Soap context from the web service proxy class
    SoapContext requestContext = javaService.RequestSoapContext;
    // Adds the security token
    requestContext.Security.Tokens.Add(securityToken);
    // Specifies the security token to sign the message with
    requestContext.Security.Elements.Add(new MessageSignature(securityToken));
    requestContext.Security.EncodedMustUnderstand = 0;

    // Specify the url that the web service proxy should use, overrides web.config value
    javaService.Url = _javaWebServiceURL;
    javaService.Timeout = 60000;

    var result = javaService.DummyCall(123);

    DB:2.49:Wse 2.0 To Wcf Connect To Java Service cs

    Thanks for the response. I will try out your recommendations and let you know how it goes.

  • RELEVANCY SCORE 2.49

    DB:2.49:Problem Using Rsapkcs1signatureformatter 7z


    Hi, I have to generate message digest using SHA1 algorithm to produce 160 bit number. Then message digest is encrypted with signer's private key(using RSA ECB and PKCS#1 v1.5 padding) and convert to printable hex format.For the above specification i have tried the following code, I am getting Invalid PKCS#1 padding: no leading zero error (java.security.SignatureException, javax.crypto.BadPaddingException:)on the receiver end. They are using Java interface to handle these messages.Is there any other method to create ECB and PKCS#1 v1.5 padding using .NET ? Imports System.SecurityImports System.Security.CryptographyImports Microsoft.Web.Services.SecurityImports Microsoft.Web.Services.Security.X509 Public Function fnDigitalSign1(ByVal strMessage As String) As String Dim rsaCSP As New System.Security.Cryptography.RSACryptoServiceProviderDim toEncrypt() As ByteDim encrypted() As ByteDim digest() As Byte Dim enc As New UnicodeEncodingtoEncrypt = enc.GetBytes(strMessage)'compute hash with algorithm specified as here we have SHA1Dim sha1Algo As New SHA1Manageddigest = sha1Algo.ComputeHash(toEncrypt)Dim cert As X509Certificate = fnGetCertificate() 'Here i am getting correct certificate only. If cert.SupportsDigitalSignature() ThenDim objRSA As RSAPKCS1SignatureFormatterobjRSA = New RSAPKCS1SignatureFormatter(cert.Key)objRSA.SetHashAlgorithm("SHA1")encrypted = objRSA.CreateSignature(digest)End If Dim strHEX As String = getHEXformat(encrypted) End Function Private Function fnGetCertificate() As X509Certificate Dim store As X509CertificateStorestore = X509CertificateStore.CurrentUserStore(X509CertificateStore.MyStore)store.OpenRead()Dim cert As X509Certificate = store.Certificates(0) Return cert End FunctionPrivate Function getHEXformat(ByVal encrypted() As Byte) As StringDim b As ByteDim hexString As StringFor Each b In encryptedhexString += String.Format("{0:X2}", b)NextReturn hexString.ToLower End Function'And I am trying with RSACryptoService provider also Public Function fnDigitalSign2(ByVal strMessage As String) As String Try Dim cert As X509Certificate = fnGetCertificate()'Receiver's PublicDim receiver_public As RSAParameters = cert.Key.ExportParameters(False)Dim sender_private As RSAParameters = cert.Key.ExportParameters(True)Dim toEncrypt() As ByteDim encrypted() As ByteDim cipher() As ByteDim digest() As Byte toEncrypt = fnGetEncodedBytes(strMessage, SelectEncode.ASCII)'compute hash with algorithm specified as here we have SHA1 digest = fnComputeSHA1Hash(toEncrypt) Dim rsaCSP As New System.Security.Cryptography.RSACryptoServiceProvider rsaCSP.ImportParameters(sender_private)cipher = rsaCSP.Encrypt(digest, False) 'False to create PKCS#1 padding Return getHEXformat(cipher) Catch ex As Exception End Try End Function '

    DB:2.49:Problem Using Rsapkcs1signatureformatter 7z

    Hi, I have to generate message digest using SHA1 algorithm to produce 160 bit number. Then message digest is encrypted with signer's private key(using RSA ECB and PKCS#1 v1.5 padding) and convert to printable hex format.For the above specification i have tried the following code, I am getting Invalid PKCS#1 padding: no leading zero error (java.security.SignatureException, javax.crypto.BadPaddingException:)on the receiver end. They are using Java interface to handle these messages.Is there any other method to create ECB and PKCS#1 v1.5 padding using .NET ? Imports System.SecurityImports System.Security.CryptographyImports Microsoft.Web.Services.SecurityImports Microsoft.Web.Services.Security.X509 Public Function fnDigitalSign1(ByVal strMessage As String) As String Dim rsaCSP As New System.Security.Cryptography.RSACryptoServiceProviderDim toEncrypt() As ByteDim encrypted() As ByteDim digest() As Byte Dim enc As New UnicodeEncodingtoEncrypt = enc.GetBytes(strMessage)'compute hash with algorithm specified as here we have SHA1Dim sha1Algo As New SHA1Manageddigest = sha1Algo.ComputeHash(toEncrypt)Dim cert As X509Certificate = fnGetCertificate() 'Here i am getting correct certificate only. If cert.SupportsDigitalSignature() ThenDim objRSA As RSAPKCS1SignatureFormatterobjRSA = New RSAPKCS1SignatureFormatter(cert.Key)objRSA.SetHashAlgorithm("SHA1")encrypted = objRSA.CreateSignature(digest)End If Dim strHEX As String = getHEXformat(encrypted) End Function Private Function fnGetCertificate() As X509Certificate Dim store As X509CertificateStorestore = X509CertificateStore.CurrentUserStore(X509CertificateStore.MyStore)store.OpenRead()Dim cert As X509Certificate = store.Certificates(0) Return cert End FunctionPrivate Function getHEXformat(ByVal encrypted() As Byte) As StringDim b As ByteDim hexString As StringFor Each b In encryptedhexString += String.Format("{0:X2}", b)NextReturn hexString.ToLower End Function'And I am trying with RSACryptoService provider also Public Function fnDigitalSign2(ByVal strMessage As String) As String Try Dim cert As X509Certificate = fnGetCertificate()'Receiver's PublicDim receiver_public As RSAParameters = cert.Key.ExportParameters(False)Dim sender_private As RSAParameters = cert.Key.ExportParameters(True)Dim toEncrypt() As ByteDim encrypted() As ByteDim cipher() As ByteDim digest() As Byte toEncrypt = fnGetEncodedBytes(strMessage, SelectEncode.ASCII)'compute hash with algorithm specified as here we have SHA1 digest = fnComputeSHA1Hash(toEncrypt) Dim rsaCSP As New System.Security.Cryptography.RSACryptoServiceProvider rsaCSP.ImportParameters(sender_private)cipher = rsaCSP.Encrypt(digest, False) 'False to create PKCS#1 padding Return getHEXformat(cipher) Catch ex As Exception End Try End Function '