Example usage for org.bouncycastle.pkcs PKCS10CertificationRequest getEncoded

List of usage examples for org.bouncycastle.pkcs PKCS10CertificationRequest getEncoded

Introduction

In this page you can find the example usage for org.bouncycastle.pkcs PKCS10CertificationRequest getEncoded.

Prototype

public byte[] getEncoded() throws IOException 

Source Link

Usage

From source file:org.wso2.carbon.certificate.mgt.core.util.CSRGenerator.java

License:Open Source License

/**
 * Generate the desired CSR for signing/*from   ww  w.  j a va2  s  .c om*/
 *
 * @param sigAlg
 * @param keyPair
 * @return
 */
public byte[] generateCSR(String sigAlg, KeyPair keyPair) {
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    PrintStream printStream = new PrintStream(outStream);
    try {
        PKCS10CertificationRequestBuilder p10Builder = new JcaPKCS10CertificationRequestBuilder(
                new X500Principal("CN=Requested Test Certificate"), keyPair.getPublic());
        JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder("SHA256withRSA");
        ContentSigner signer = csBuilder.build(keyPair.getPrivate());
        PKCS10CertificationRequest csr = p10Builder.build(signer);
        return csr.getEncoded();
    } catch (OperatorCreationException ex) {
        log.error("Error while Key generation operation", ex);
    } catch (IOException ex) {
        log.error("Error while generating CSR,ex");
    }
    return new byte[0];
}

From source file:org.wso2.carbon.identity.certificateauthority.dao.CsrDAO.java

License:Open Source License

private String addCsr(PKCS10CertificationRequest request, String userName, int tenantID, String userStoreDomain,
        String transactionId) throws CaException {
    String csrSerialNo = new BigInteger(32, new SecureRandom()).toString();
    Connection connection = null;
    Date requestDate = new Date();
    String sql = null;/*from  www . j a  v a  2s  . co m*/
    PreparedStatement prepStmt = null;
    RDN[] orgRdNs = request.getSubject().getRDNs(BCStyle.O);
    String organization = "";
    if (orgRdNs.length > 0) {
        organization = orgRdNs[0].getFirst().getValue().toString();
    }
    RDN[] cnRdNs = request.getSubject().getRDNs(BCStyle.CN);
    String commonName = "";
    if (cnRdNs.length > 0) {
        commonName = cnRdNs[0].getFirst().getValue().toString();
    }
    try {
        log.debug("adding csr file to database");
        connection = JDBCPersistenceManager.getInstance().getDBConnection();
        sql = "INSERT INTO CA_CSR_STORE (CSR_CONTENT, STATUS, USER_NAME, REQUESTED_DATE, SERIAL_NO, TENANT_ID,COMMON_NAME,ORGANIZATION,UM_DOMAIN_NAME,TRANSACTION_ID) VALUES (?,?,?,?,?,?,?,?,?,?) ";
        prepStmt = connection.prepareStatement(sql);
        prepStmt.setBlob(1, new ByteArrayInputStream(request.getEncoded()));
        prepStmt.setString(2, CsrStatus.PENDING.toString());
        prepStmt.setString(3, userName);
        prepStmt.setTimestamp(4, new Timestamp(requestDate.getTime()));
        prepStmt.setString(5, csrSerialNo);
        prepStmt.setInt(6, tenantID);
        prepStmt.setString(7, commonName);
        prepStmt.setString(8, organization);
        prepStmt.setString(9, userStoreDomain);
        prepStmt.setString(10, transactionId);
        prepStmt.execute();
        connection.commit();
    } catch (IdentityException e) {
        String errorMsg = "Error when getting an Identity Persistence Store instance.";
        log.error(errorMsg, e);
        throw new CaException(errorMsg, e);
    } catch (SQLException e) {
        log.error("Error when executing the SQL : " + sql, e);
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    } finally {
        IdentityDatabaseUtil.closeAllConnections(connection, null, prepStmt);
    }
    return csrSerialNo;
}

From source file:org.xipki.commons.security.shell.CertRequestGenCommandSupport.java

License:Open Source License

@Override
protected Object doExecute() throws Exception {
    hashAlgo = hashAlgo.trim().toUpperCase();
    if (hashAlgo.indexOf('-') != -1) {
        hashAlgo = hashAlgo.replaceAll("-", "");
    }/*  w w w. j  a va  2s.  c o  m*/

    if (needExtensionTypes == null) {
        needExtensionTypes = new LinkedList<>();
    }

    if (wantExtensionTypes == null) {
        wantExtensionTypes = new LinkedList<>();
    }

    // SubjectAltNames
    List<Extension> extensions = new LinkedList<>();

    ASN1OctetString extnValue = createExtnValueSubjectAltName();
    if (extnValue != null) {
        ASN1ObjectIdentifier oid = Extension.subjectAlternativeName;
        extensions.add(new Extension(oid, false, extnValue));
        needExtensionTypes.add(oid.getId());
    }

    // SubjectInfoAccess
    extnValue = createExtnValueSubjectInfoAccess();
    if (extnValue != null) {
        ASN1ObjectIdentifier oid = Extension.subjectInfoAccess;
        extensions.add(new Extension(oid, false, extnValue));
        needExtensionTypes.add(oid.getId());
    }

    // Keyusage
    if (isNotEmpty(keyusages)) {
        Set<KeyUsage> usages = new HashSet<>();
        for (String usage : keyusages) {
            usages.add(KeyUsage.getKeyUsage(usage));
        }
        org.bouncycastle.asn1.x509.KeyUsage extValue = X509Util.createKeyUsage(usages);
        ASN1ObjectIdentifier extType = Extension.keyUsage;
        extensions.add(new Extension(extType, false, extValue.getEncoded()));
        needExtensionTypes.add(extType.getId());
    }

    // ExtendedKeyusage
    if (isNotEmpty(extkeyusages)) {
        ExtendedKeyUsage extValue = X509Util.createExtendedUsage(textToAsn1ObjectIdentifers(extkeyusages));
        ASN1ObjectIdentifier extType = Extension.extendedKeyUsage;
        extensions.add(new Extension(extType, false, extValue.getEncoded()));
        needExtensionTypes.add(extType.getId());
    }

    // QcEuLimitValue
    if (isNotEmpty(qcEuLimits)) {
        ASN1EncodableVector vec = new ASN1EncodableVector();
        for (String m : qcEuLimits) {
            StringTokenizer st = new StringTokenizer(m, ":");
            try {
                String currencyS = st.nextToken();
                String amountS = st.nextToken();
                String exponentS = st.nextToken();

                Iso4217CurrencyCode currency;
                try {
                    int intValue = Integer.parseInt(currencyS);
                    currency = new Iso4217CurrencyCode(intValue);
                } catch (NumberFormatException ex) {
                    currency = new Iso4217CurrencyCode(currencyS);
                }

                int amount = Integer.parseInt(amountS);
                int exponent = Integer.parseInt(exponentS);

                MonetaryValue monterayValue = new MonetaryValue(currency, amount, exponent);
                QCStatement statment = new QCStatement(ObjectIdentifiers.id_etsi_qcs_QcLimitValue,
                        monterayValue);
                vec.add(statment);
            } catch (Exception ex) {
                throw new Exception("invalid qc-eu-limit '" + m + "'");
            }
        }

        ASN1ObjectIdentifier extType = Extension.qCStatements;
        ASN1Sequence extValue = new DERSequence(vec);
        extensions.add(new Extension(extType, false, extValue.getEncoded()));
        needExtensionTypes.add(extType.getId());
    }

    // biometricInfo
    if (biometricType != null && biometricHashAlgo != null && biometricFile != null) {
        TypeOfBiometricData tmpBiometricType = StringUtil.isNumber(biometricType)
                ? new TypeOfBiometricData(Integer.parseInt(biometricType))
                : new TypeOfBiometricData(new ASN1ObjectIdentifier(biometricType));

        ASN1ObjectIdentifier tmpBiometricHashAlgo = AlgorithmUtil.getHashAlg(biometricHashAlgo);
        byte[] biometricBytes = IoUtil.read(biometricFile);
        MessageDigest md = MessageDigest.getInstance(tmpBiometricHashAlgo.getId());
        md.reset();
        byte[] tmpBiometricDataHash = md.digest(biometricBytes);

        DERIA5String tmpSourceDataUri = null;
        if (biometricUri != null) {
            tmpSourceDataUri = new DERIA5String(biometricUri);
        }
        BiometricData biometricData = new BiometricData(tmpBiometricType,
                new AlgorithmIdentifier(tmpBiometricHashAlgo), new DEROctetString(tmpBiometricDataHash),
                tmpSourceDataUri);

        ASN1EncodableVector vec = new ASN1EncodableVector();
        vec.add(biometricData);

        ASN1ObjectIdentifier extType = Extension.biometricInfo;
        ASN1Sequence extValue = new DERSequence(vec);
        extensions.add(new Extension(extType, false, extValue.getEncoded()));
        needExtensionTypes.add(extType.getId());
    } else if (biometricType == null && biometricHashAlgo == null && biometricFile == null) {
        // Do nothing
    } else {
        throw new Exception("either all of biometric triples (type, hash algo, file)"
                + " must be set or none of them should be set");
    }

    for (Extension addExt : getAdditionalExtensions()) {
        extensions.add(addExt);
    }

    needExtensionTypes.addAll(getAdditionalNeedExtensionTypes());
    wantExtensionTypes.addAll(getAdditionalWantExtensionTypes());

    if (isNotEmpty(needExtensionTypes) || isNotEmpty(wantExtensionTypes)) {
        ExtensionExistence ee = new ExtensionExistence(textToAsn1ObjectIdentifers(needExtensionTypes),
                textToAsn1ObjectIdentifers(wantExtensionTypes));
        extensions.add(new Extension(ObjectIdentifiers.id_xipki_ext_cmpRequestExtensions, false,
                ee.toASN1Primitive().getEncoded()));
    }

    ConcurrentContentSigner signer = getSigner(new SignatureAlgoControl(rsaMgf1, dsaPlain));

    Map<ASN1ObjectIdentifier, ASN1Encodable> attributes = new HashMap<>();
    if (CollectionUtil.isNonEmpty(extensions)) {
        attributes.put(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest,
                new Extensions(extensions.toArray(new Extension[0])));
    }

    if (StringUtil.isNotBlank(challengePassword)) {
        attributes.put(PKCSObjectIdentifiers.pkcs_9_at_challengePassword,
                new DERPrintableString(challengePassword));
    }

    SubjectPublicKeyInfo subjectPublicKeyInfo;
    if (signer.getCertificate() != null) {
        Certificate cert = Certificate.getInstance(signer.getCertificate().getEncoded());
        subjectPublicKeyInfo = cert.getSubjectPublicKeyInfo();
    } else {
        subjectPublicKeyInfo = KeyUtil.createSubjectPublicKeyInfo(signer.getPublicKey());
    }

    X500Name subjectDn = getSubject(subject);
    PKCS10CertificationRequest csr = generateRequest(signer, subjectPublicKeyInfo, subjectDn, attributes);

    File file = new File(outputFilename);
    saveVerbose("saved CSR to file", file, csr.getEncoded());
    return null;
}

From source file:org.xipki.security.shell.CertRequestGenCommand.java

License:Open Source License

@Override
protected Object _doExecute() throws Exception {
    P10RequestGenerator p10Gen = new P10RequestGenerator();

    hashAlgo = hashAlgo.trim().toUpperCase();
    if (hashAlgo.indexOf('-') != -1) {
        hashAlgo = hashAlgo.replaceAll("-", "");
    }/*ww w .  j a v a2s.  c  om*/

    if (needExtensionTypes == null) {
        needExtensionTypes = new LinkedList<>();
    }

    // SubjectAltNames
    List<Extension> extensions = new LinkedList<>();
    if (isNotEmpty(subjectAltNames)) {
        extensions.add(P10RequestGenerator.createExtensionSubjectAltName(subjectAltNames, false));
        needExtensionTypes.add(Extension.subjectAlternativeName.getId());
    }

    // SubjectInfoAccess
    if (isNotEmpty(subjectInfoAccesses)) {
        extensions.add(P10RequestGenerator.createExtensionSubjectInfoAccess(subjectInfoAccesses, false));
        needExtensionTypes.add(Extension.subjectInfoAccess.getId());
    }

    // Keyusage
    if (isNotEmpty(keyusages)) {
        Set<KeyUsage> usages = new HashSet<>();
        for (String usage : keyusages) {
            usages.add(KeyUsage.getKeyUsage(usage));
        }
        org.bouncycastle.asn1.x509.KeyUsage extValue = X509Util.createKeyUsage(usages);
        ASN1ObjectIdentifier extType = Extension.keyUsage;
        extensions.add(new Extension(extType, false, extValue.getEncoded()));
        needExtensionTypes.add(extType.getId());
    }

    // ExtendedKeyusage
    if (isNotEmpty(extkeyusages)) {
        Set<ASN1ObjectIdentifier> oids = new HashSet<>(SecurityUtil.textToASN1ObjectIdentifers(extkeyusages));
        ExtendedKeyUsage extValue = X509Util.createExtendedUsage(oids);
        ASN1ObjectIdentifier extType = Extension.extendedKeyUsage;
        extensions.add(new Extension(extType, false, extValue.getEncoded()));
        needExtensionTypes.add(extType.getId());
    }

    if (isNotEmpty(needExtensionTypes) || isNotEmpty(wantExtensionTypes)) {
        ExtensionExistence ee = new ExtensionExistence(
                SecurityUtil.textToASN1ObjectIdentifers(needExtensionTypes),
                SecurityUtil.textToASN1ObjectIdentifers(wantExtensionTypes));
        extensions.add(new Extension(ObjectIdentifiers.id_xipki_ext_cmpRequestExtensions, false,
                ee.toASN1Primitive().getEncoded()));
    }

    ConcurrentContentSigner identifiedSigner = getSigner(hashAlgo, new SignatureAlgoControl(rsaMgf1, dsaPlain));
    Certificate cert = Certificate.getInstance(identifiedSigner.getCertificate().getEncoded());

    X500Name subjectDN;
    if (subject != null) {
        subjectDN = new X500Name(subject);
    } else {
        subjectDN = cert.getSubject();
    }

    SubjectPublicKeyInfo subjectPublicKeyInfo = cert.getSubjectPublicKeyInfo();

    ContentSigner signer = identifiedSigner.borrowContentSigner();

    PKCS10CertificationRequest p10Req;
    try {
        p10Req = p10Gen.generateRequest(signer, subjectPublicKeyInfo, subjectDN, extensions);
    } finally {
        identifiedSigner.returnContentSigner(signer);
    }

    File file = new File(outputFilename);
    saveVerbose("saved PKCS#10 request to file", file, p10Req.getEncoded());
    return null;
}

From source file:ServiceCert.MsgAtoS.java

public MsgAtoS(String loginA, byte[] digestOfpass, PKCS10CertificationRequest dataArrayOfcsr) {
    try {/*from w w  w  .  j  a v a 2s. com*/
        this.loginA = loginA;
        this.digestOfpass = digestOfpass;
        this.dataArrayOfcsr = dataArrayOfcsr.getEncoded();
    } catch (IOException ex) {
        System.err.println(ex.toString());
        ;
    }
}

From source file:SS.CSRRequestSS.java

public void run() {

    try {/*  w w w .  j ava  2  s. c o m*/
        KeyPair keyPair = generateKeyPair();
        privKey = keyPair.getPrivate();

        //Cration du CSR a envoyer au Serveur de Certificat
        PKCS10CertificationRequest csr = CSRManager.generateCSR(login, keyPair);

        System.out.print("Cration de l'objet  envoy :");
        InfoCSR serviceCSR = new InfoCSR(csr.getEncoded(), login, digest(password));
        System.out.println("OK");

        System.out.print("Transformation en tableau de bytes");
        byte[] bytesCSR = ObjectToByte(serviceCSR);
        System.out.println("OK");

        System.out.print("Rcupration de la cl publique du Serveur de Certificats :");
        PublicKey pubKey = getPublicKeyInFile();
        System.out.println("OK");

        System.out.print("Chiffrement de l'objet :");
        byte[] encrypted = encrypt(pubKey, bytesCSR);
        System.out.println("OK");

        System.out.print("Instanciation de la classe pour l'envoi et la rception:");
        readAndWriteObject readWrite2 = new readAndWriteObject(s);
        System.out.println("OK");

        System.out.print("Envoi de la demande de certification :");
        readWrite2.writeObject2(encrypted);
        System.out.println("OK");

        System.out.print("Rception de l'objet contenant le certificat :");
        byte[] receive = readWrite2.readObject2();

        System.out.println("OK");

        System.out.print("Rconstruction du certificat :");
        X509Certificate cert = getCertBytes(receive);
        System.out.println("OK");

        KeyStoreManager storeManager = null;
        try {
            storeManager = new KeyStoreManager();
        } catch (Exception e) {
            System.out.println("CSRRequestSS => KeyStoreManager: " + e);
        }

        System.out.print("Enregistrement du certificat ru dans le keystore : ");
        storeManager.saveOwnCert(login, cert);
        System.out.println("OK");

        System.out.print("Enregistrement de la cl priv dans le keystore : ");
        storeManager.saveOwnKey(login, privKey, cert);
        System.out.println("OK");

        System.out.println("==========Liste des certificats=========");
        storeManager.listCertAliasses(login);

        close();
        System.out.println("CSRRequestSS closed!");

    } catch (Exception e) {
        System.out.println("CSRRequestSS => run : " + e);
    }
}