Example usage for org.bouncycastle.asn1.pkcs PKCSObjectIdentifiers sha1WithRSAEncryption

List of usage examples for org.bouncycastle.asn1.pkcs PKCSObjectIdentifiers sha1WithRSAEncryption

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.pkcs PKCSObjectIdentifiers sha1WithRSAEncryption.

Prototype

ASN1ObjectIdentifier sha1WithRSAEncryption

To view the source code for org.bouncycastle.asn1.pkcs PKCSObjectIdentifiers sha1WithRSAEncryption.

Click Source Link

Document

PKCS#1: 1.2.840.113549.1.1.5

Usage

From source file:org.ejbca.core.protocol.ocsp.ProtocolOcspHttpTest.java

License:Open Source License

/**
 * This test tests that the OCSP response contains is signed by the preferred signature algorithm specified in the request.
 * //from   w  w  w .  j  av  a  2s .  c  o  m
 * @throws Exception
*/
@Test
@Deprecated // This test verifies legacy behavior from EJBCA 6.1.0 and should be removed when we no longer need to support it
public void testSigAlgExtensionLegacy() throws Exception {
    loadUserCert(this.caid);

    // Try sending a request where the preferred signature algorithm in the extension is expected to be used to sign the response.

    // set ocsp configuration
    Map<String, String> map = new HashMap<String, String>();
    map.put("ocsp.signaturealgorithm",
            AlgorithmConstants.SIGALG_SHA256_WITH_RSA + ";" + AlgorithmConstants.SIGALG_SHA1_WITH_RSA);
    this.helper.alterConfig(map);

    ASN1EncodableVector algVec = new ASN1EncodableVector();
    algVec.add(X9ObjectIdentifiers.ecdsa_with_SHA256);
    algVec.add(PKCSObjectIdentifiers.sha1WithRSAEncryption);
    ASN1Sequence algSeq = new DERSequence(algVec);
    ExtensionsGenerator extgen = new ExtensionsGenerator();
    // RFC 6960: id-pkix-ocsp-pref-sig-algs   OBJECT IDENTIFIER ::= { id-pkix-ocsp 8 } 
    extgen.addExtension(new ASN1ObjectIdentifier(OCSPObjectIdentifiers.id_pkix_ocsp + ".8"), false, algSeq);
    Extensions exts = extgen.generate();
    assertNotNull(exts);

    OCSPReqBuilder gen = new OCSPReqBuilder();
    gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), cacert,
            ocspTestCert.getSerialNumber()), exts);
    gen.setRequestExtensions(exts);
    OCSPReq req = gen.build();
    assertTrue(req.hasExtensions());

    BasicOCSPResp response = helper.sendOCSPGet(req.getEncoded(), null, OCSPRespBuilder.SUCCESSFUL, 200);
    assertNotNull("Could not retrieve response, test could not continue.", response);
    assertEquals(PKCSObjectIdentifiers.sha1WithRSAEncryption, response.getSignatureAlgOID());

    // Try sending a request where the preferred signature algorithm is not compatible with the signing key, but 
    // the configured algorithm is. Expected a response signed using the first configured algorithm

    algVec = new ASN1EncodableVector();
    algVec.add(X9ObjectIdentifiers.ecdsa_with_SHA256);
    algSeq = new DERSequence(algVec);

    extgen = new ExtensionsGenerator();
    extgen.addExtension(new ASN1ObjectIdentifier(OCSPObjectIdentifiers.id_pkix_ocsp + ".8"), false, algSeq);
    exts = extgen.generate();
    assertNotNull(exts);

    gen = new OCSPReqBuilder();
    gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), cacert,
            ocspTestCert.getSerialNumber()), exts);
    gen.setRequestExtensions(exts);
    req = gen.build();
    assertTrue(req.hasExtensions());

    response = helper.sendOCSPGet(req.getEncoded(), null, OCSPRespBuilder.SUCCESSFUL, 200);
    assertNotNull("Could not retrieve response, test could not continue.", response);
    assertEquals(PKCSObjectIdentifiers.sha256WithRSAEncryption, response.getSignatureAlgOID());
}

From source file:org.ejbca.core.protocol.ocsp.ProtocolOcspHttpTest.java

License:Open Source License

/** This test tests that the OCSP response contains is signed by the preferred signature algorithm specified in the request. */
/* Example of the ASN.1 dump (with friendly names from the RFC added ) of what the extensions should look like.
 * /*from  w w  w  .ja  v a 2s . c o  m*/
 * Note that we have left out the optional
 *  PreferredSignatureAlgorithm.pubKeyAlgIdentifier
 * and
 *  AlgorithmIdentifier.parameters
 *  
 *               ...
 *  75  48:     requestExtensions [2] {
 *  77  46:       Extensions ::= SEQUENCE {
 *  79  44:         Extension ::= SEQUENCE {
 *  81   9:           extnID OBJECT IDENTIFIER '1 3 6 1 5 5 7 48 1 8'
 *  92  31:           extnValue OCTET STRING, encapsulates {
 *  94  29:             PreferredSignatureAlgorithms ::= SEQUENCE {
 *  96  12:               PreferredSignatureAlgorithm ::= SEQUENCE {
 *  98  10:                 sigIdentifier AlgorithmIdentifier ::= SEQUENCE {
 * 100   8:                   algorithm OBJECT IDENTIFIER
 *        :                     ecdsaWithSHA256 (1 2 840 10045 4 3 2)
 *        :                   }
 *        :                 }
 * 110  13:               PreferredSignatureAlgorithm ::= SEQUENCE {
 * 112  11:                 sigIdentifier AlgorithmIdentifier ::= SEQUENCE {
 * 114   9:                   algorithm OBJECT IDENTIFIER
 *        :                     sha1WithRSAEncryption (1 2 840 113549 1 1 5)
 *        :                   }
 *        :                 ...
 */
@Test
public void testSigAlgExtension() throws Exception {
    log.trace(">testSigAlgExtensionNew");
    loadUserCert(caid);
    // Try sending a request where the preferred signature algorithm in the extension is expected to be used to sign the response.
    // set ocsp configuration
    final Map<String, String> map = new HashMap<String, String>();
    map.put("ocsp.signaturealgorithm",
            AlgorithmConstants.SIGALG_SHA256_WITH_RSA + ";" + AlgorithmConstants.SIGALG_SHA1_WITH_RSA);
    helper.alterConfig(map);
    final ASN1Sequence preferredSignatureAlgorithms = getPreferredSignatureAlgorithms(
            X9ObjectIdentifiers.ecdsa_with_SHA256, PKCSObjectIdentifiers.sha1WithRSAEncryption);
    final ExtensionsGenerator extensionsGenerator = new ExtensionsGenerator();
    // RFC 6960: id-pkix-ocsp-pref-sig-algs   OBJECT IDENTIFIER ::= { id-pkix-ocsp 8 } 
    extensionsGenerator.addExtension(new ASN1ObjectIdentifier(OCSPObjectIdentifiers.id_pkix_ocsp + ".8"), false,
            preferredSignatureAlgorithms);
    final Extensions extensions = extensionsGenerator.generate();
    assertNotNull(extensions);
    final OCSPReqBuilder ocspReqBuilder = new OCSPReqBuilder();
    ocspReqBuilder.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), cacert,
            ocspTestCert.getSerialNumber()));
    ocspReqBuilder.setRequestExtensions(extensions);
    final OCSPReq ocspRequest = ocspReqBuilder.build();
    assertTrue(ocspRequest.hasExtensions());
    log.debug("base64 encoded request: " + new String(Base64.encode(ocspRequest.getEncoded(), false)));
    final BasicOCSPResp response1 = helper.sendOCSPGet(ocspRequest.getEncoded(), null,
            OCSPRespBuilder.SUCCESSFUL, 200);
    assertNotNull("Could not retrieve response, test could not continue.", response1);
    assertEquals(PKCSObjectIdentifiers.sha1WithRSAEncryption, response1.getSignatureAlgOID());
}

From source file:org.ejbca.core.protocol.ws.client.NestedCrmfRequestMissingStoredCertTestCommand.java

License:Open Source License

/**
 * Runs the command//from w ww .ja  va2  s .  c  o  m
 *
 * @throws IllegalAdminCommandException Error in command args
 * @throws ErrorAdminCommandException Error running command
 */
public void execute() throws IllegalAdminCommandException, ErrorAdminCommandException {

    try {

        CertRequest certReq = genCertReq(userDN, null);

        PKIMessage certMsg = genPKIMessage(false, certReq);
        if (certMsg == null) {
            getPrintStream().println("No certificate request.");
            System.exit(-1);
        }
        AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);
        certMsg.getHeader().setProtectionAlg(pAlg);
        certMsg.getHeader().setSenderKID(new DEROctetString("EMPTY".getBytes()));
        PKIMessage signedMsg = signPKIMessage(certMsg, innerSignKey);
        addExtraCert(signedMsg, innerCertificate);
        if (signedMsg == null) {
            getPrintStream().println("No protected message.");
            System.exit(-1);
        }

        PKIHeader myPKIHeader = new PKIHeader(new DERInteger(2),
                new GeneralName(new X509Name("CN=CMSSender,C=SE")),
                new GeneralName(new X509Name(((X509Certificate) cacert).getSubjectDN().getName())));
        myPKIHeader.setMessageTime(new DERGeneralizedTime(new Date()));
        // senderNonce
        myPKIHeader.setSenderNonce(new DEROctetString(nonce));
        // TransactionId
        myPKIHeader.setTransactionID(new DEROctetString(nonce));
        //myPKIHeader.addGeneralInfo(new InfoTypeAndValue(ASN1Sequence.getInstance(crmfMsg)));
        byte[] recipNonce = new byte[16];
        random.nextBytes(recipNonce);
        myPKIHeader.setRecipNonce(new DEROctetString(recipNonce));

        PKIBody myPKIBody = new PKIBody(signedMsg, 20); // NestedMessageContent
        PKIMessage myPKIMessage = new PKIMessage(myPKIHeader, myPKIBody);
        KeyPair signkeys = KeyTools.genKeys("1024", "RSA");
        PKIMessage cmsMessage = signPKIMessage(myPKIMessage, signkeys.getPrivate());

        reqId = signedMsg.getBody().getIr().getCertReqMsg(0).getCertReq().getCertReqId().getValue().intValue();
        final ByteArrayOutputStream bao = new ByteArrayOutputStream();
        final DEROutputStream out = new DEROutputStream(bao);
        out.writeObject(cmsMessage);
        final byte[] ba = bao.toByteArray();
        // Send request and receive response
        final byte[] resp = sendCmp(ba);
        if (resp == null || resp.length <= 0) {
            getPrintStream().println("No response message.");
            System.exit(-1);
        }

        PKIMessage respObject = PKIMessage
                .getInstance(new ASN1InputStream(new ByteArrayInputStream(resp)).readObject());
        if (respObject == null) {
            getPrintStream().println("No response message object could be optained");
            System.exit(-1);
        }

        PKIBody body = respObject.getBody();
        if (body.getTagNo() != 23) {
            getPrintStream().println("Expected tagnr 23, but found " + body.getTagNo());
            System.exit(-1);
        }
        getPrintStream().println("Response tagnr checked 23 ok");
        getPrintStream()
                .println("FailInfo error code: " + body.getError().getPKIStatus().getFailInfo().getPadBits());
        getPrintStream().println(
                "Error Message: " + body.getError().getPKIStatus().getStatusString().getString(0).getString());

    } catch (IOException e) {
        e.printStackTrace(getPrintStream());
        System.exit(-1);
    } catch (InvalidKeyException e) {
        e.printStackTrace(getPrintStream());
        System.exit(-1);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace(getPrintStream());
        System.exit(-1);
    } catch (SignatureException e) {
        e.printStackTrace(getPrintStream());
        System.exit(-1);
    } catch (NoSuchProviderException e) {
        e.printStackTrace(getPrintStream());
        System.exit(-1);
    } catch (CertificateEncodingException e) {
        e.printStackTrace(getPrintStream());
        System.exit(-1);
    } catch (InvalidAlgorithmParameterException e) {
        e.printStackTrace(getPrintStream());
        System.exit(-1);
    } catch (Exception e) {
        e.printStackTrace(getPrintStream());
        System.exit(-1);
    }

    getPrintStream().println("Test successfull");
}

From source file:org.ejbca.core.protocol.ws.client.NestedCrmfRequestWrongSignatureTestCommand.java

License:Open Source License

private void init(String[] args) {

    FileInputStream file_inputstream;
    try {// ww  w .j av a 2s. c o m
        String pwd = args[ARG_KEYSTOREPASSWORD];
        String certNameInKeystore = args[ARG_CERTNAMEINKEYSTORE];
        file_inputstream = new FileInputStream(args[ARG_KEYSTOREPATH]);
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        keyStore.load(file_inputstream, pwd.toCharArray());
        System.out.println("Keystore size " + keyStore.size());
        Enumeration aliases = keyStore.aliases();
        while (aliases.hasMoreElements()) {
            System.out.println(aliases.nextElement());
        }
        Key key = keyStore.getKey(certNameInKeystore, pwd.toCharArray());
        getPrintStream().println("Key information " + key.getAlgorithm() + " " + key.getFormat());
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(key.getEncoded());
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        innerSignKey = keyFactory.generatePrivate(keySpec);
        innerCertificate = keyStore.getCertificate(certNameInKeystore);
    } catch (FileNotFoundException e2) {
        e2.printStackTrace(getPrintStream());
        System.exit(-1);
    } catch (KeyStoreException e) {
        e.printStackTrace(getPrintStream());
        System.exit(-1);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace(getPrintStream());
        System.exit(-1);
    } catch (CertificateException e) {
        e.printStackTrace(getPrintStream());
        System.exit(-1);
    } catch (IOException e) {
        e.printStackTrace(getPrintStream());
        System.exit(-1);
    } catch (UnrecoverableKeyException e) {
        e.printStackTrace(getPrintStream());
        System.exit(-1);
    } catch (InvalidKeySpecException e) {
        e.printStackTrace(getPrintStream());
        System.exit(-1);
    }

    try {
        KeyPair outerSignKeys = KeyTools.genKeys("1024", "RSA");
        outerSignKey = outerSignKeys.getPrivate();
        X509Certificate signCert = CertTools.genSelfCert("CN=cmpStressTest,C=SE", 5000000, null,
                outerSignKeys.getPrivate(), outerSignKeys.getPublic(),
                PKCSObjectIdentifiers.sha1WithRSAEncryption.getId(), true, "BC");

        ArrayList<Certificate> certCollection = new ArrayList<Certificate>();
        certCollection.add(signCert);
        byte[] pemRaCert = CertTools.getPEMFromCerts(certCollection);

        FileOutputStream out = new FileOutputStream(new File("/opt/racerts/cmpStressTest.pem"));
        out.write(pemRaCert);
        out.close();
    } catch (NoSuchAlgorithmException e1) {
        e1.printStackTrace(getPrintStream());
        System.exit(-1);
    } catch (NoSuchProviderException e1) {
        e1.printStackTrace(getPrintStream());
        System.exit(-1);
    } catch (InvalidAlgorithmParameterException e1) {
        e1.printStackTrace(getPrintStream());
        System.exit(-1);
    } catch (InvalidKeyException e) {
        e.printStackTrace(getPrintStream());
        System.exit(-1);
    } catch (CertificateEncodingException e) {
        e.printStackTrace(getPrintStream());
        System.exit(-1);
    } catch (SignatureException e) {
        e.printStackTrace(getPrintStream());
        System.exit(-1);
    } catch (IllegalStateException e) {
        e.printStackTrace(getPrintStream());
        System.exit(-1);
    } catch (FileNotFoundException e) {
        e.printStackTrace(getPrintStream());
        System.exit(-1);
    } catch (IOException e) {
        e.printStackTrace(getPrintStream());
        System.exit(-1);
    } catch (CertificateException e) {
        e.printStackTrace(getPrintStream());
        System.exit(-1);
    }

}

From source file:org.ejbca.core.protocol.ws.client.NestedCrmfRequestWrongSignatureTestCommand.java

License:Open Source License

/**
 * Runs the command//from   w w w . j av  a 2  s .c  o m
 *
 * @throws IllegalAdminCommandException Error in command args
 * @throws ErrorAdminCommandException Error running command
 */
public void execute() throws IllegalAdminCommandException, ErrorAdminCommandException {

    try {

        CertRequest certReq = genCertReq(userDN, null);

        PKIMessage certMsg = genPKIMessage(false, certReq);
        if (certMsg == null) {
            getPrintStream().println("No certificate request.");
            System.exit(-1);
        }
        AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);
        certMsg.getHeader().setProtectionAlg(pAlg);
        certMsg.getHeader().setSenderKID(new DEROctetString("EMPTY".getBytes()));
        PKIMessage signedMsg = signPKIMessage(certMsg, innerSignKey);
        addExtraCert(signedMsg, innerCertificate);
        if (signedMsg == null) {
            getPrintStream().println("No protected message.");
            System.exit(-1);
        }

        PKIHeader myPKIHeader = new PKIHeader(new DERInteger(2),
                new GeneralName(new X509Name("CN=CMSSender,C=SE")),
                new GeneralName(new X509Name(((X509Certificate) cacert).getSubjectDN().getName())));
        myPKIHeader.setMessageTime(new DERGeneralizedTime(new Date()));
        // senderNonce
        myPKIHeader.setSenderNonce(new DEROctetString(nonce));
        // TransactionId
        myPKIHeader.setTransactionID(new DEROctetString(nonce));
        //myPKIHeader.addGeneralInfo(new InfoTypeAndValue(ASN1Sequence.getInstance(crmfMsg)));
        byte[] recipNonce = new byte[16];
        random.nextBytes(recipNonce);
        myPKIHeader.setRecipNonce(new DEROctetString(recipNonce));

        PKIBody myPKIBody = new PKIBody(signedMsg, 20); // NestedMessageContent
        PKIMessage myPKIMessage = new PKIMessage(myPKIHeader, myPKIBody);
        PKIMessage signedCrmfMsg2 = signPKIMessage(certMsg, outerSignKey);
        myPKIMessage.setProtection(signedCrmfMsg2.getProtection());

        reqId = signedMsg.getBody().getIr().getCertReqMsg(0).getCertReq().getCertReqId().getValue().intValue();
        final ByteArrayOutputStream bao = new ByteArrayOutputStream();
        final DEROutputStream out = new DEROutputStream(bao);
        out.writeObject(myPKIMessage);
        final byte[] ba = bao.toByteArray();
        // Send request and receive response
        final byte[] resp = sendCmp(ba);
        if (resp == null || resp.length <= 0) {
            getPrintStream().println("No response message.");
            System.exit(-1);
        }
        getPrintStream().println("Got response");
        /*
        if ( !checkCmpResponseGeneral(resp, false) ) {
           System.exit(-1);
        }
        getPrintStream().println("Response checked OK");
        */
        PKIMessage respObject = PKIMessage
                .getInstance(new ASN1InputStream(new ByteArrayInputStream(resp)).readObject());
        if (respObject == null) {
            getPrintStream().println("No response message object could be optained");
            System.exit(-1);
        }
        getPrintStream().println("Response object created OK");

        PKIBody body = respObject.getBody();

        /*
        if(body.getTagNo() == 23) {
           getPrintStream().println("Response tagnr 23 checked OK");
           getPrintStream().println("FailInfo error code: " + body.getError().getPKIStatus().getFailInfo().intValue());
           getPrintStream().println("Error Message: " + body.getError().getPKIStatus().getStatusString().getString(0).getString());             
        } else if(body.getTagNo() == 1) {
          final X509Certificate cert = checkCmpCertRepMessage(resp, reqId);
          if ( cert==null ) {
             getPrintStream().println("No certificate was created");
          } else {
             getPrintStream().println("Certificate for " + userDN + " was created with the serialnumber: " + cert.getSerialNumber().toString());
          }             
        } else {
           getPrintStream().println("Expected tagnr 23 or 1, but found " + body.getTagNo() + ". ERROR");
        }
        */

        if (body.getTagNo() != 23) {
            getPrintStream().println("Expected tagnr 23 or 1. Found tagnr " + body.getTagNo() + ".");
            if (body.getTagNo() == 1) {

                final X509Certificate cert = checkCmpCertRepMessage(resp, reqId);
                if (cert == null) {
                    getPrintStream().println("No certificate was created");
                } else {
                    getPrintStream().println("Certificate for " + userDN
                            + " was created with the serialnumber: " + cert.getSerialNumber().toString());
                }
            }
        } else {
            getPrintStream().println("Response tagnr 23 checked OK");
            getPrintStream().println(
                    "FailInfo error code: " + body.getError().getPKIStatus().getFailInfo().getPadBits());
            getPrintStream().println("Error Message: "
                    + body.getError().getPKIStatus().getStatusString().getString(0).getString());
        }

    } catch (IOException e) {
        e.printStackTrace(getPrintStream());
        System.exit(-1);
    } catch (InvalidKeyException e) {
        e.printStackTrace(getPrintStream());
        System.exit(-1);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace(getPrintStream());
        System.exit(-1);
    } catch (SignatureException e) {
        e.printStackTrace(getPrintStream());
        System.exit(-1);
    } catch (NoSuchProviderException e) {
        e.printStackTrace(getPrintStream());
        System.exit(-1);
    } catch (CertificateEncodingException e) {
        e.printStackTrace(getPrintStream());
        System.exit(-1);
    } catch (InvalidAlgorithmParameterException e) {
        e.printStackTrace(getPrintStream());
        System.exit(-1);
    } catch (Exception e) {
        e.printStackTrace(getPrintStream());
        System.exit(-1);
    }

    getPrintStream().println("Test successfull");
}

From source file:org.ejbca.ui.cli.CMPNestedMessageStressTest.java

License:Open Source License

@Override
protected void execute(String[] args) {
    final String hostName;
    final String keystoreFile;
    final String keystorePassword;
    final String certNameInKeystore;
    final int numberOfThreads;
    final int waitTime;
    final String certFileName;
    final File certFile;
    final String keyId;
    final int port;
    final boolean isHttp;
    final String urlPath;
    final String resultFilePrefix;
    if (args.length < 6) {
        System.out.println(args[0]
                + " <host name> <CA certificate file name> <CMS keystore (p12)> <keystore password> <CMS certificate in keystore> [<number of threads>] [<wait time (ms) between each thread is started>] [<KeyId to be sent to server>] [<port>] [<URL path of servlet. use 'null' to get EJBCA (not proxy) default>] [<certificate file prefix. set this if you want all received certificates stored on files>]");
        System.out.println(/* w  ww . j av  a2 s .c  o  m*/
                "EJBCA build configuration requirements: cmp.operationmode=ra, cmp.allowraverifypopo=true, cmp.authenticationmodule=EndEntityCertificate, cmp.authenticationparameters=AdminCA1, checkadminauthorization=false, cmp.racertificatepath=/tmp/racerts");
        System.out.println(
                "EJBCA build configuration optional: cmp.ra.certificateprofile=KeyId cmp.ra.endentityprofile=KeyId (used when the KeyId argument should be used as profile name).");
        return;
    }
    hostName = args[1];
    certFileName = args[2];
    certFile = new File(certFileName);
    keystoreFile = args[3];
    keystorePassword = args[4];
    certNameInKeystore = args[5];
    numberOfThreads = args.length > 6 ? Integer.parseInt(args[6].trim()) : 1;
    waitTime = args.length > 7 ? Integer.parseInt(args[7].trim()) : 0;
    keyId = args.length > 8 ? args[8].trim() : "EMPTY";
    port = args.length > 9 ? Integer.parseInt(args[9].trim()) : 8080;
    isHttp = true;
    urlPath = args.length > 10 && args[10].toLowerCase().indexOf("null") < 0 ? args[10].trim() : null;
    resultFilePrefix = args.length > 11 ? args[11].trim() : null;

    CryptoProviderTools.installBCProviderIfNotAvailable();

    Certificate innerCert = null;
    PrivateKey innerSignKey = null;

    FileInputStream file_inputstream;
    try {
        file_inputstream = new FileInputStream(keystoreFile);
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        keyStore.load(file_inputstream, keystorePassword.toCharArray());
        System.out.println("Keystore size " + keyStore.size());
        Enumeration aliases = keyStore.aliases();
        while (aliases.hasMoreElements()) {
            System.out.println(aliases.nextElement());
        }
        Key key = keyStore.getKey(certNameInKeystore, keystorePassword.toCharArray());
        System.out.println("Key information " + key.getAlgorithm() + " " + key.getFormat());
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(key.getEncoded());
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        innerSignKey = keyFactory.generatePrivate(keySpec);
        innerCert = keyStore.getCertificate(certNameInKeystore);
    } catch (FileNotFoundException e2) {
        e2.printStackTrace();
        System.exit(-1);
    } catch (KeyStoreException e) {
        e.printStackTrace();
        System.exit(-1);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        System.exit(-1);
    } catch (CertificateException e) {
        e.printStackTrace();
        System.exit(-1);
    } catch (IOException e) {
        e.printStackTrace();
        System.exit(-1);
    } catch (UnrecoverableKeyException e) {
        e.printStackTrace();
        System.exit(-1);
    } catch (InvalidKeySpecException e) {
        e.printStackTrace();
        System.exit(-1);
    }

    KeyPair outerSignKeys = null;
    try {
        outerSignKeys = KeyTools.genKeys("1024", "RSA");
        X509Certificate signCert = CertTools.genSelfCert("CN=cmpStressTest,C=SE", 5000000, null,
                outerSignKeys.getPrivate(), outerSignKeys.getPublic(),
                PKCSObjectIdentifiers.sha1WithRSAEncryption.getId(), true, "BC");

        Vector<Certificate> certCollection = new Vector<Certificate>();
        certCollection.add(signCert);
        byte[] pemRaCert = CertTools.getPEMFromCerts(certCollection);

        FileOutputStream out = new FileOutputStream(new File("/tmp/racerts/cmpStressTest.pem"));
        out.write(pemRaCert);
        out.close();
    } catch (NoSuchAlgorithmException e1) {
        e1.printStackTrace();
        System.exit(-1);
    } catch (NoSuchProviderException e1) {
        e1.printStackTrace();
        System.exit(-1);
    } catch (InvalidAlgorithmParameterException e1) {
        e1.printStackTrace();
        System.exit(-1);
    } catch (InvalidKeyException e) {
        e.printStackTrace();
        System.exit(-1);
    } catch (CertificateEncodingException e) {
        e.printStackTrace();
        System.exit(-1);
    } catch (SignatureException e) {
        e.printStackTrace();
        System.exit(-1);
    } catch (IllegalStateException e) {
        e.printStackTrace();
        System.exit(-1);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        System.exit(-1);
    } catch (IOException e) {
        e.printStackTrace();
        System.exit(-1);
    } catch (CertificateException e) {
        e.printStackTrace();
        System.exit(-1);
    }

    try {
        if (!certFile.canRead()) {
            System.out.println("File " + certFile.getCanonicalPath() + " not a valid file name.");
            return;
        }
        //            Security.addProvider(new BouncyCastleProvider());
        new StressTest(hostName, port, isHttp, new FileInputStream(certFile), numberOfThreads, waitTime, keyId,
                urlPath, resultFilePrefix, outerSignKeys.getPrivate(), innerSignKey, innerCert);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.ejbca.ui.cmpclient.CmpClientMessageHelper.java

License:Open Source License

public PKIMessage createProtectedMessage(PKIMessage pkimessage, String authModule, String authParameter,
        final String keystorePath, final String keystorepwd, final boolean verbose) throws InvalidKeyException,
        NoSuchAlgorithmException, NoSuchProviderException, UnrecoverableKeyException, KeyStoreException,
        CertificateException, FileNotFoundException, IOException, SecurityException, SignatureException {

    if (StringUtils.equalsIgnoreCase(authModule, CmpConfiguration.AUTHMODULE_REG_TOKEN_PWD)) {
        if (verbose) {
            log.info("Authentication module used is " + CmpConfiguration.AUTHMODULE_REG_TOKEN_PWD + ". "
                    + "PKI message returned as is.");
        }//from   w  w w  . j a va2 s  .  c om
        return pkimessage;
    }

    if (StringUtils.equalsIgnoreCase(authModule, CmpConfiguration.AUTHMODULE_HMAC)) {
        if (verbose) {
            log.info("Creating protected PKIMessage using: authentication module=" + authModule
                    + ", authentication parameter=" + authParameter);
        }
        return protectPKIMessageWithHMAC(pkimessage, false, authParameter, 567);
    }

    if (StringUtils.equalsIgnoreCase(authModule, CmpConfiguration.AUTHMODULE_ENDENTITY_CERTIFICATE)) {
        if (verbose) {
            log.info("Creating protected PKIMessage using authentication module: " + authModule);
            log.info("Certificate in extraCerts field should be issued by: " + authParameter);
            log.info("Keystore: " + keystorePath + "  -  Keystore password: " + keystorepwd);
        }

        final KeyStore keystore = getKeystore(keystorePath, keystorepwd);
        Certificate extraCert = getCertFromKeystore(keystore, authParameter);
        //Object[] adminData = getAdminDataFromKeystore(keystore, keystorepwd, authParameter, verbose);
        //Certificate adminCert = (Certificate) adminData[0];
        if (verbose) {
            log.info("Certificate to be attached in the extraCerts field extracted from keystore. "
                    + "Certificate SubjectDN: " + CertTools.getSubjectDN(extraCert)
                    + " - Certificate issuerDN: " + CertTools.getIssuerDN(extraCert) + " - "
                    + "Certificate serialnumber: " + CertTools.getSerialNumberAsString(extraCert)
                    + " - Certificate fingerprint: " + CertTools.getFingerprintAsString(extraCert));
        }

        PrivateKey signKey = (PrivateKey) getKeyFromKeystore(keystore, keystorepwd, authParameter);

        CMPCertificate[] extraCerts = getCMPCerts(extraCert);
        AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);
        return buildCertBasedPKIProtection(pkimessage, extraCerts, signKey, pAlg.getAlgorithm().getId(), "BC",
                verbose);
    }

    log.info("Unrecognized authentication module: " + authModule);
    return null;
}

From source file:org.openconcerto.modules.finance.payment.ebics.crypto.X509CertificateGenerator.java

License:Open Source License

/**
 * This method implements the public one, but offers an additional parameter which is only used
 * when creating a new CA, namely the export alias to use.
 * /*from   w  w  w. j  a v a2s . c o  m*/
 * @param commonName @see #createCertificate(String, int, String, String)
 * @param validityDays @see #createCertificate(String, int, String, String)
 * @param exportFile @see #createCertificate(String, int, String, String)
 * @param exportPassword @see #createCertificate(String, int, String, String)
 * @param exportAlias If this additional parameter is null, a default value will be used as the
 *        "friendly name" in the PKCS12 file.
 * @return @see #createCertificate(String, int, String, String)
 * 
 * @see #X509CertificateGenerator(boolean)
 */
protected boolean createCertificate(String commonName, int validityDays, String exportFile,
        String exportPassword, String exportAlias) throws IOException, InvalidKeyException, SecurityException,
        SignatureException, NoSuchAlgorithmException, DataLengthException, CryptoException, KeyStoreException,
        CertificateException, InvalidKeySpecException {
    if (commonName == null || exportFile == null || exportPassword == null || validityDays < 1) {
        throw new IllegalArgumentException("Can not work with null parameter");
    }

    System.out.println("Generating certificate for distinguished common subject name '" + commonName
            + "', valid for " + validityDays + " days");
    SecureRandom sr = new SecureRandom();

    // the JCE representation
    PublicKey pubKey;
    PrivateKey privKey;

    // the BCAPI representation
    RSAPrivateCrtKeyParameters privateKey = null;

    System.out.println("Creating RSA keypair");
    // generate the keypair for the new certificate

    RSAKeyPairGenerator gen = new RSAKeyPairGenerator();
    // TODO: what are these values??
    gen.init(new RSAKeyGenerationParameters(BigInteger.valueOf(0x10001), sr, 1024, 80));
    AsymmetricCipherKeyPair keypair = gen.generateKeyPair();
    System.out
            .println("Generated keypair, extracting components and creating public structure for certificate");
    RSAKeyParameters publicKey = (RSAKeyParameters) keypair.getPublic();
    privateKey = (RSAPrivateCrtKeyParameters) keypair.getPrivate();
    // used to get proper encoding for the certificate
    RSAPublicKeyStructure pkStruct = new RSAPublicKeyStructure(publicKey.getModulus(), publicKey.getExponent());
    System.out.println("New public key is '" + new String(Hex.encode(pkStruct.getEncoded())) + ", exponent="
            + publicKey.getExponent() + ", modulus=" + publicKey.getModulus());
    // TODO: these two lines should go away
    // JCE format needed for the certificate - because getEncoded() is necessary...
    pubKey = KeyFactory.getInstance("RSA")
            .generatePublic(new RSAPublicKeySpec(publicKey.getModulus(), publicKey.getExponent()));
    // and this one for the KeyStore
    privKey = KeyFactory.getInstance("RSA")
            .generatePrivate(new RSAPrivateCrtKeySpec(publicKey.getModulus(), publicKey.getExponent(),
                    privateKey.getExponent(), privateKey.getP(), privateKey.getQ(), privateKey.getDP(),
                    privateKey.getDQ(), privateKey.getQInv()));

    Calendar expiry = Calendar.getInstance();
    expiry.add(Calendar.DAY_OF_YEAR, validityDays);

    X500Name x509Name = new X500Name("CN=" + commonName);

    V3TBSCertificateGenerator certGen = new V3TBSCertificateGenerator();
    certGen.setSerialNumber(new DERInteger(BigInteger.valueOf(System.currentTimeMillis())));
    if (caCert != null) {
        // Attention: this is a catch! Just using
        // "new X509Name(caCert.getSubjectDN().getName())" will not work!
        // I don't know why, because the issuerDN strings look similar with both versions.
        certGen.setIssuer(PrincipalUtil.getSubjectX509Principal(caCert));
    } else {
        // aha, no CA set, which means that we should create a self-signed certificate (called
        // from createCA)
        certGen.setIssuer(x509Name);
    }
    certGen.setSubject(x509Name);

    // TODO GM:
    DERObjectIdentifier sigOID = PKCSObjectIdentifiers.sha1WithRSAEncryption;// DERObjectIdentifier.
                                                                             // X509Util.getAlgorithmOID(CertificateSignatureAlgorithm);
    AlgorithmIdentifier sigAlgId = new AlgorithmIdentifier(sigOID, new DERNull());
    certGen.setSignature(sigAlgId);
    // certGen.setSubjectPublicKeyInfo(new SubjectPublicKeyInfo(sigAlgId,
    // pkStruct.toASN1Object()));
    // TODO: why does the coding above not work? - make me work without PublicKey class
    certGen.setSubjectPublicKeyInfo(new SubjectPublicKeyInfo(
            (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(pubKey.getEncoded())).readObject()));
    certGen.setStartDate(new Time(new Date(System.currentTimeMillis())));
    certGen.setEndDate(new Time(expiry.getTime()));

    // These X509v3 extensions are not strictly necessary, but be nice and provide them...
    Hashtable extensions = new Hashtable();
    Vector extOrdering = new Vector();
    addExtensionHelper(X509Extension.subjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(pubKey),
            extOrdering, extensions);
    if (caCert != null) {
        // again: only if we have set CA
        addExtensionHelper(X509Extension.authorityKeyIdentifier, false,
                new AuthorityKeyIdentifierStructure(caCert), extOrdering, extensions);
    } else {
        // but if we create a new self-signed cert, set its capability to be a CA
        // this is a critical extension (true)!
        addExtensionHelper(X509Extension.basicConstraints, true, new BasicConstraints(0), extOrdering,
                extensions);
    }
    certGen.setExtensions(new X509Extensions(extOrdering, extensions));

    System.out.println("Certificate structure generated, creating SHA1 digest");
    // attention: hard coded to be SHA1+RSA!
    SHA1Digest digester = new SHA1Digest();
    AsymmetricBlockCipher rsa = new PKCS1Encoding(new RSAEngine());
    TBSCertificateStructure tbsCert = certGen.generateTBSCertificate();

    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    DEROutputStream dOut = new DEROutputStream(bOut);
    dOut.writeObject(tbsCert);

    // and now sign
    byte[] signature;

    byte[] certBlock = bOut.toByteArray();
    // first create digest
    System.out.println("Block to sign is '" + new String(Hex.encode(certBlock)) + "'");
    digester.update(certBlock, 0, certBlock.length);
    byte[] hash = new byte[digester.getDigestSize()];
    digester.doFinal(hash, 0);
    // and sign that
    if (caCert != null) {
        rsa.init(true, caPrivateKey);
    } else {
        // no CA - self sign
        System.out.println("No CA has been set, creating self-signed certificate as a new CA");
        rsa.init(true, privateKey);
    }
    DigestInfo dInfo = new DigestInfo(new AlgorithmIdentifier(X509ObjectIdentifiers.id_SHA1, null), hash);
    byte[] digest = dInfo.getEncoded(ASN1Encodable.DER);
    signature = rsa.processBlock(digest, 0, digest.length);

    System.out.println("SHA1/RSA signature of digest is '" + new String(Hex.encode(signature)) + "'");

    // and finally construct the certificate structure
    ASN1EncodableVector v = new ASN1EncodableVector();

    v.add(tbsCert);
    v.add(sigAlgId);
    v.add(new DERBitString(signature));

    X509CertificateObject clientCert = new X509CertificateObject(
            new X509CertificateStructure(new DERSequence(v)));
    System.out.println("Verifying certificate for correct signature with CA public key");
    /*
     * if (caCert != null) { clientCert.verify(caCert.getPublicKey()); } else {
     * clientCert.verify(pubKey); }
     */

    // and export as PKCS12 formatted file along with the private key and the CA certificate
    System.out.println("Exporting certificate in PKCS12 format");

    PKCS12BagAttributeCarrier bagCert = clientCert;
    // if exportAlias is set, use that, otherwise a default name
    bagCert.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName,
            new DERBMPString(exportAlias == null ? CertificateExportFriendlyName : exportAlias));
    bagCert.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
            new SubjectKeyIdentifierStructure(pubKey));

    // this does not work as in the example
    /*
     * PKCS12BagAttributeCarrier bagKey = (PKCS12BagAttributeCarrier)privKey;
     * bagKey.setBagAttribute( PKCSObjectIdentifiers.pkcs_9_at_localKeyId, new
     * SubjectKeyIdentifierStructure(tmpKey));
     */

    JDKPKCS12KeyStore store;

    store = new JDKPKCS12KeyStore.BCPKCS12KeyStore();
    store.engineLoad(null, null);

    FileOutputStream fOut = new FileOutputStream(exportFile);
    X509Certificate[] chain;

    if (caCert != null) {
        chain = new X509Certificate[2];
        // first the client, then the CA certificate - this is the expected order for a
        // certificate chain
        chain[0] = clientCert;
        chain[1] = caCert;
    } else {
        // for a self-signed certificate, there is no chain...
        chain = new X509Certificate[1];
        chain[0] = clientCert;
    }

    store.engineSetKeyEntry(exportAlias == null ? KeyExportFriendlyName : exportAlias, privKey,
            exportPassword.toCharArray(), chain);
    store.engineStore(fOut, exportPassword.toCharArray());

    return true;
}

From source file:org.xipki.common.util.AlgorithmUtil.java

License:Open Source License

static public String getSignatureAlgoName(final AlgorithmIdentifier sigAlgId) throws NoSuchAlgorithmException {
    ASN1ObjectIdentifier algOid = sigAlgId.getAlgorithm();

    if (X9ObjectIdentifiers.ecdsa_with_SHA1.equals(algOid)) {
        return "SHA1withECDSA";
    } else if (X9ObjectIdentifiers.ecdsa_with_SHA224.equals(algOid)) {
        return "SHA224withECDSA";
    } else if (X9ObjectIdentifiers.ecdsa_with_SHA256.equals(algOid)) {
        return "SHA256withECDSA";
    } else if (X9ObjectIdentifiers.ecdsa_with_SHA384.equals(algOid)) {
        return "SHA384withECDSA";
    } else if (X9ObjectIdentifiers.ecdsa_with_SHA512.equals(algOid)) {
        return "SHA512WITHECDSA";
    } else if (BSIObjectIdentifiers.ecdsa_plain_SHA1.equals(algOid)) {
        return "SHA1WITHPLAIN-ECDSA";
    } else if (BSIObjectIdentifiers.ecdsa_plain_SHA224.equals(algOid)) {
        return "SHA224WITHPLAIN-ECDSA";
    } else if (BSIObjectIdentifiers.ecdsa_plain_SHA256.equals(algOid)) {
        return "SHA256WITHPLAIN-ECDSA";
    } else if (BSIObjectIdentifiers.ecdsa_plain_SHA384.equals(algOid)) {
        return "SHA384WITHPLAIN-ECDSA";
    } else if (BSIObjectIdentifiers.ecdsa_plain_SHA512.equals(algOid)) {
        return "SHA512WITHPLAIN-ECDSA";
    } else if (X9ObjectIdentifiers.id_dsa_with_sha1.equals(algOid)) {
        return "SHA1withDSA";
    } else if (X9ObjectIdentifiers.id_dsa_with_sha1.equals(algOid)) {
        return "SHA1withDSA";
    } else if (NISTObjectIdentifiers.dsa_with_sha224.equals(algOid)) {
        return "SHA224withDSA";
    } else if (NISTObjectIdentifiers.dsa_with_sha256.equals(algOid)) {
        return "SHA256withDSA";
    } else if (NISTObjectIdentifiers.dsa_with_sha384.equals(algOid)) {
        return "SHA384withDSA";
    } else if (NISTObjectIdentifiers.dsa_with_sha512.equals(algOid)) {
        return "SHA512withDSA";
    } else if (PKCSObjectIdentifiers.sha1WithRSAEncryption.equals(algOid)) {
        return "SHA1withRSA";
    } else if (PKCSObjectIdentifiers.sha224WithRSAEncryption.equals(algOid)) {
        return "SHA224withRSA";
    } else if (PKCSObjectIdentifiers.sha256WithRSAEncryption.equals(algOid)) {
        return "SHA256withRSA";
    } else if (PKCSObjectIdentifiers.sha384WithRSAEncryption.equals(algOid)) {
        return "SHA384withRSA";
    } else if (PKCSObjectIdentifiers.sha512WithRSAEncryption.equals(algOid)) {
        return "SHA512withRSA";
    } else if (PKCSObjectIdentifiers.id_RSASSA_PSS.equals(algOid)) {
        RSASSAPSSparams param = RSASSAPSSparams.getInstance(sigAlgId.getParameters());
        ASN1ObjectIdentifier digestAlgOid = param.getHashAlgorithm().getAlgorithm();
        if (X509ObjectIdentifiers.id_SHA1.equals(digestAlgOid)) {
            return "SHA1withRSAandMGF1";
        } else if (NISTObjectIdentifiers.id_sha256.equals(digestAlgOid)) {
            return "SHA256withRSAandMGF1";
        } else if (NISTObjectIdentifiers.id_sha384.equals(digestAlgOid)) {
            return "SHA384withRSAandMGF1";
        } else if (NISTObjectIdentifiers.id_sha512.equals(digestAlgOid)) {
            return "SHA512withRSAandMGF1";
        } else {/*from ww w .j  av  a2s . c  om*/
            throw new NoSuchAlgorithmException("unsupported digest algorithm " + digestAlgOid.getId());
        }
    } else {
        throw new NoSuchAlgorithmException("unsupported signature algorithm " + algOid.getId());
    }
}

From source file:org.xipki.common.util.AlgorithmUtil.java

License:Open Source License

static public AlgorithmIdentifier getSignatureAlgoId(final String signatureAlgoName)
        throws NoSuchAlgorithmException {
    String algoS = signatureAlgoName.replaceAll("-", "");

    AlgorithmIdentifier signatureAlgId;/*from   ww  w .  jav a2s.com*/
    if ("SHA1withRSAandMGF1".equalsIgnoreCase(algoS) || "SHA224withRSAandMGF1".equalsIgnoreCase(algoS)
            || "SHA256withRSAandMGF1".equalsIgnoreCase(algoS) || "SHA384withRSAandMGF1".equalsIgnoreCase(algoS)
            || "SHA512withRSAandMGF1".equalsIgnoreCase(algoS)) {
        ASN1ObjectIdentifier hashAlgo;
        if ("SHA1withRSAandMGF1".equalsIgnoreCase(algoS)) {
            hashAlgo = X509ObjectIdentifiers.id_SHA1;
        } else if ("SHA224withRSAandMGF1".equalsIgnoreCase(algoS)) {
            hashAlgo = NISTObjectIdentifiers.id_sha224;
        } else if ("SHA256withRSAandMGF1".equalsIgnoreCase(algoS)) {
            hashAlgo = NISTObjectIdentifiers.id_sha256;
        } else if ("SHA384withRSAandMGF1".equalsIgnoreCase(algoS)) {
            hashAlgo = NISTObjectIdentifiers.id_sha384;
        } else if ("SHA512withRSAandMGF1".equalsIgnoreCase(algoS)) {
            hashAlgo = NISTObjectIdentifiers.id_sha512;
        } else {
            throw new NoSuchAlgorithmException("should not reach here, unknown algorithm " + algoS);
        }

        signatureAlgId = AlgorithmUtil.buildRSAPSSAlgorithmIdentifier(hashAlgo);
    } else {
        boolean withNullParam = false;
        ASN1ObjectIdentifier algOid;
        if ("SHA1withRSA".equalsIgnoreCase(algoS) || "RSAwithSHA1".equalsIgnoreCase(algoS)
                || PKCSObjectIdentifiers.sha1WithRSAEncryption.getId().equals(algoS)) {
            algOid = PKCSObjectIdentifiers.sha1WithRSAEncryption;
            withNullParam = true;
        } else if ("SHA224withRSA".equalsIgnoreCase(algoS) || "RSAwithSHA224".equalsIgnoreCase(algoS)
                || PKCSObjectIdentifiers.sha224WithRSAEncryption.getId().equals(algoS)) {
            algOid = PKCSObjectIdentifiers.sha224WithRSAEncryption;
            withNullParam = true;
        } else if ("SHA256withRSA".equalsIgnoreCase(algoS) || "RSAwithSHA256".equalsIgnoreCase(algoS)
                || PKCSObjectIdentifiers.sha256WithRSAEncryption.getId().equals(algoS)) {
            algOid = PKCSObjectIdentifiers.sha256WithRSAEncryption;
            withNullParam = true;
        } else if ("SHA384withRSA".equalsIgnoreCase(algoS) || "RSAwithSHA384".equalsIgnoreCase(algoS)
                || PKCSObjectIdentifiers.sha384WithRSAEncryption.getId().equals(algoS)) {
            algOid = PKCSObjectIdentifiers.sha384WithRSAEncryption;
            withNullParam = true;
        } else if ("SHA512withRSA".equalsIgnoreCase(algoS) || "RSAwithSHA512".equalsIgnoreCase(algoS)
                || PKCSObjectIdentifiers.sha512WithRSAEncryption.getId().equals(algoS)) {
            algOid = PKCSObjectIdentifiers.sha512WithRSAEncryption;
            withNullParam = true;
        } else if ("SHA1withECDSA".equalsIgnoreCase(algoS) || "ECDSAwithSHA1".equalsIgnoreCase(algoS)
                || X9ObjectIdentifiers.ecdsa_with_SHA1.getId().equals(algoS)) {
            algOid = X9ObjectIdentifiers.ecdsa_with_SHA1;
        } else if ("SHA224withECDSA".equalsIgnoreCase(algoS) || "ECDSAwithSHA224".equalsIgnoreCase(algoS)
                || X9ObjectIdentifiers.ecdsa_with_SHA224.getId().equals(algoS)) {
            algOid = X9ObjectIdentifiers.ecdsa_with_SHA224;
        } else if ("SHA256withECDSA".equalsIgnoreCase(algoS) || "ECDSAwithSHA256".equalsIgnoreCase(algoS)
                || X9ObjectIdentifiers.ecdsa_with_SHA256.getId().equals(algoS)) {
            algOid = X9ObjectIdentifiers.ecdsa_with_SHA256;
        } else if ("SHA384withECDSA".equalsIgnoreCase(algoS) || "ECDSAwithSHA384".equalsIgnoreCase(algoS)
                || X9ObjectIdentifiers.ecdsa_with_SHA384.getId().equals(algoS)) {
            algOid = X9ObjectIdentifiers.ecdsa_with_SHA384;
        } else if ("SHA512withECDSA".equalsIgnoreCase(algoS) || "ECDSAwithSHA512".equalsIgnoreCase(algoS)
                || X9ObjectIdentifiers.ecdsa_with_SHA512.getId().equals(algoS)) {
            algOid = X9ObjectIdentifiers.ecdsa_with_SHA512;
        } else if ("SHA1withPlainECDSA".equalsIgnoreCase(algoS) || "PlainECDSAwithSHA1".equalsIgnoreCase(algoS)
                || BSIObjectIdentifiers.ecdsa_plain_SHA1.getId().equals(algoS)) {
            algOid = BSIObjectIdentifiers.ecdsa_plain_SHA1;
        } else if ("SHA224withPlainECDSA".equalsIgnoreCase(algoS)
                || "PlainECDSAwithSHA224".equalsIgnoreCase(algoS)
                || BSIObjectIdentifiers.ecdsa_plain_SHA224.getId().equals(algoS)) {
            algOid = BSIObjectIdentifiers.ecdsa_plain_SHA224;
        } else if ("SHA256withPlainECDSA".equalsIgnoreCase(algoS)
                || "PlainECDSAwithSHA256".equalsIgnoreCase(algoS)
                || BSIObjectIdentifiers.ecdsa_plain_SHA256.getId().equals(algoS)) {
            algOid = BSIObjectIdentifiers.ecdsa_plain_SHA256;
        } else if ("SHA384withPlainECDSA".equalsIgnoreCase(algoS)
                || "PlainECDSAwithSHA384".equalsIgnoreCase(algoS)
                || BSIObjectIdentifiers.ecdsa_plain_SHA384.getId().equals(algoS)) {
            algOid = BSIObjectIdentifiers.ecdsa_plain_SHA384;
        } else if ("SHA512withPlainECDSA".equalsIgnoreCase(algoS)
                || "PlainECDSAwithSHA512".equalsIgnoreCase(algoS)
                || BSIObjectIdentifiers.ecdsa_plain_SHA512.getId().equals(algoS)) {
            algOid = BSIObjectIdentifiers.ecdsa_plain_SHA512;
        } else if ("SHA1withDSA".equalsIgnoreCase(algoS) || "DSAwithSHA1".equalsIgnoreCase(algoS)
                || X9ObjectIdentifiers.id_dsa_with_sha1.getId().equals(algoS)) {
            algOid = X9ObjectIdentifiers.id_dsa_with_sha1;
        } else if ("SHA224withDSA".equalsIgnoreCase(algoS) || "DSAwithSHA224".equalsIgnoreCase(algoS)
                || NISTObjectIdentifiers.dsa_with_sha224.getId().equals(algoS)) {
            algOid = NISTObjectIdentifiers.dsa_with_sha224;
        } else if ("SHA256withDSA".equalsIgnoreCase(algoS) || "DSAwithSHA256".equalsIgnoreCase(algoS)
                || NISTObjectIdentifiers.dsa_with_sha256.getId().equals(algoS)) {
            algOid = NISTObjectIdentifiers.dsa_with_sha256;
        } else if ("SHA384withDSA".equalsIgnoreCase(algoS) || "DSAwithSHA384".equalsIgnoreCase(algoS)
                || NISTObjectIdentifiers.dsa_with_sha384.getId().equals(algoS)) {
            algOid = NISTObjectIdentifiers.dsa_with_sha384;
        } else if ("SHA512withDSA".equalsIgnoreCase(algoS) || "DSAwithSHA512".equalsIgnoreCase(algoS)
                || NISTObjectIdentifiers.dsa_with_sha512.getId().equals(algoS)) {
            algOid = NISTObjectIdentifiers.dsa_with_sha512;
        } else {
            throw new NoSuchAlgorithmException("unsupported signature algorithm " + algoS);
        }

        signatureAlgId = withNullParam ? new AlgorithmIdentifier(algOid, DERNull.INSTANCE)
                : new AlgorithmIdentifier(algOid);
    }

    return signatureAlgId;
}