Example usage for java.math BigInteger toString

List of usage examples for java.math BigInteger toString

Introduction

In this page you can find the example usage for java.math BigInteger toString.

Prototype

public String toString(int radix) 

Source Link

Document

Returns the String representation of this BigInteger in the given radix.

Usage

From source file:org.piwik.SimplePiwikTracker.java

/**
 * Creates an MD5 hash for the given input.
 * /*from   www.  ja v  a 2  s . com*/
 * @param input the input string
 * @return the hashed string
 */
private String md5(final String input) {
    String retVal = "";
    try {
        final byte[] b = MessageDigest.getInstance("MD5").digest(input.getBytes());
        final java.math.BigInteger bi = new java.math.BigInteger(1, b);
        retVal = bi.toString(16);
        while (retVal.length() < 32) {
            retVal = "0" + retVal;
        }
    } catch (final NoSuchAlgorithmException e) {
        LOGGER.log(Level.SEVERE, "Error while creating a md5 hash", e);
    }
    return retVal;
}

From source file:edu.mit.mobile.android.locast.sync.AbsMediaSync.java

private String sha1Sum(String data) {
    if (mDigest == null) {
        throw new RuntimeException("no message digest available");
    }/*from   ww  w .  j a  v  a 2  s.  c  om*/
    final byte[] ba;
    synchronized (mDigest) {
        mDigest.update(data.toString().getBytes());
        ba = mDigest.digest();
    }
    final BigInteger bi = new BigInteger(1, ba);
    final String result = bi.toString(16);
    if (result.length() % 2 != 0) {
        return "0" + result;
    }
    return result;
}

From source file:com.amazonaws.kinesis.agg.AggRecord.java

/**
 * Calculate a new explicit hash key based on the input partition key (following
 * the algorithm from the original KPL).
 * //from   w  ww  . j  ava 2 s . co m
 * @param partitionKey
 *            The partition key to seed the new explicit hash key with
 * @return An explicit hash key based on the input partition key generated using
 *         an algorithm from the original KPL.
 */
private String createExplicitHashKey(final String partitionKey) {
    BigInteger hashKey = BigInteger.ZERO;

    this.md5.reset();
    byte[] pkDigest = this.md5.digest(partitionKey.getBytes(StandardCharsets.UTF_8));

    for (int i = 0; i < this.md5.getDigestLength(); i++) {
        BigInteger p = new BigInteger(String.valueOf((int) pkDigest[i] & 0xFF)); // convert
        // to
        // unsigned
        // integer
        BigInteger shifted = p.shiftLeft((16 - i - 1) * 8);
        hashKey = hashKey.add(shifted);
    }

    return hashKey.toString(10);
}

From source file:org.ejbca.core.protocol.cmp.CrmfMessageHandler.java

/** Method that takes care of RA mode operations, i.e. when the message is authenticated with a common secret using password based encryption (pbe).
 * This method will verify the pbe and if ok  will automatically create/edit a user and issue the certificate. In RA mode we assume that the RA knows what it is doing.
 * //from  ww  w  .j a v  a  2 s .c o m
 * @param msg
 * @param crmfreq
 * @param authenticated if the CMP message has already been authenticated in another way or not
 * @return IResponseMessage that can be sent back to the client
 * @throws AuthorizationDeniedException
 * @throws EjbcaException
 * @throws ClassNotFoundException
 * @throws CesecoreException 
 */
private ResponseMessage handleRaMessage(final BaseCmpMessage msg, final CrmfRequestMessage crmfreq,
        boolean authenticated) throws AuthorizationDeniedException, EjbcaException, CesecoreException {
    final int eeProfileId; // The endEntityProfile to be used when adding users in RA mode.
    final String certProfileName; // The certificate profile to use when adding users in RA mode.
    final int certProfileId;
    final int requestId = crmfreq.getRequestId();
    final int requestType = crmfreq.getRequestType();
    // Try to find a HMAC/SHA1 protection key
    final String keyId = CmpMessageHelper.getStringFromOctets(crmfreq.getHeader().getSenderKID());
    int caId = 0; // The CA to user when adding users in RA mode
    try {
        eeProfileId = getUsedEndEntityProfileId(keyId);
        caId = getUsedCaId(keyId, eeProfileId);
        certProfileName = getUsedCertProfileName(keyId, eeProfileId);
        certProfileId = getUsedCertProfileId(certProfileName);
    } catch (CADoesntExistsException e) {
        LOG.info(INTRES.getLocalizedMessage(CMP_ERRORGENERAL, e.getMessage()), e);
        return CmpMessageHelper.createErrorMessage(msg, FailInfo.INCORRECT_DATA, e.getMessage(), requestId,
                requestType, null, keyId, this.responseProt);
    }

    ResponseMessage resp = null; // The CMP response message to be sent back to the client
    //Check the request's authenticity
    CAInfo cainfo = this.caSession.getCAInfoInternal(caId, null, true);
    final VerifyPKIMessage messageVerifyer = new VerifyPKIMessage(cainfo, this.confAlias, admin, caSession,
            endEntityAccessSession, certStoreSession, authorizationSession, endEntityProfileSession,
            authenticationProviderSession, eeManagementSession, this.cmpConfiguration);
    ICMPAuthenticationModule authenticationModule = messageVerifyer
            .getUsedAuthenticationModule(crmfreq.getPKIMessage(), null, authenticated);
    if (authenticationModule == null) {
        String errmsg = messageVerifyer.getErrorMessage();
        LOG.info(errmsg);
        return CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE,
                FailInfo.BAD_MESSAGE_CHECK, errmsg);
    }

    try {
        // Create a username and password and register the new user in EJBCA
        final UsernameGenerator gen = UsernameGenerator.getInstance(this.usernameGenParams);
        // Don't convert this DN to an ordered EJBCA DN string with CertTools.stringToBCDNString because we don't want double escaping of some characters
        final RequestMessage req = this.extendedUserDataHandler != null
                ? this.extendedUserDataHandler.processRequestMessage(crmfreq, certProfileName,
                        cmpConfiguration.getUnidDataSource(this.confAlias))
                : crmfreq;
        final X500Name dnname = req.getRequestX500Name();
        if (LOG.isDebugEnabled()) {
            LOG.debug("Creating username from base dn: " + dnname.toString());
        }
        final String username = StringTools.stripUsername(gen.generateUsername(dnname.toString()));
        final String pwd;
        if (StringUtils.equals(authenticationModule.getName(),
                CmpConfiguration.AUTHMODULE_ENDENTITY_CERTIFICATE)) {
            pwd = authenticationModule.getAuthenticationString();
        } else if (StringUtils.equals(authenticationModule.getName(), CmpConfiguration.AUTHMODULE_HMAC)) {
            if (StringUtils.equals(this.userPwdParams, "random")) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Setting 12 char random user password.");
                }
                final IPasswordGenerator pwdgen = PasswordGeneratorFactory
                        .getInstance(PasswordGeneratorFactory.PASSWORDTYPE_ALLPRINTABLE);
                pwd = pwdgen.getNewPassword(12, 12);
            } else {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Setting fixed user password from config.");
                }
                pwd = this.userPwdParams;
            }
        } else {
            //This should not run since an error would have occurred earlier if the authentication module was unknown 
            final String errMsg = "Unknown authentication module.";
            LOG.error(errMsg);
            return CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE,
                    FailInfo.BAD_MESSAGE_CHECK, errMsg);
        }
        // AltNames may be in the request template
        final String altNames = req.getRequestAltNames();
        final String email;
        final List<String> emails = CertTools.getEmailFromDN(altNames);
        emails.addAll(CertTools.getEmailFromDN(dnname.toString()));
        if (!emails.isEmpty()) {
            email = emails.get(0); // Use rfc822name or first SubjectDN email address as user email address if available
        } else {
            email = null;
        }
        final ExtendedInformation ei;
        if (this.allowCustomCertSerno) {
            // Don't even try to parse out the field if it is not allowed
            final BigInteger customCertSerno = crmfreq.getSubjectCertSerialNo();
            if (customCertSerno != null) {
                // If we have a custom certificate serial number in the request, we will pass it on to the UserData object
                ei = new ExtendedInformation();
                ei.setCertificateSerialNumber(customCertSerno);
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Custom certificate serial number: " + customCertSerno.toString(16));
                }
            } else {
                ei = null;
            }
        } else {
            ei = null;
        }
        final EndEntityInformation userdata = new EndEntityInformation(username, dnname.toString(), caId,
                altNames, email, EndEntityConstants.STATUS_NEW, new EndEntityType(EndEntityTypes.ENDUSER),
                eeProfileId, certProfileId, null, null, SecConst.TOKEN_SOFT_BROWSERGEN, 0, ei);
        userdata.setPassword(pwd);
        // Set so we have the right params in the call to processCertReq. 
        // Username and pwd in the EndEntityInformation and the IRequestMessage must match
        crmfreq.setUsername(username);
        crmfreq.setPassword(pwd);
        if (msg.getHeader().getProtectionAlg() != null) {
            crmfreq.setPreferredDigestAlg(AlgorithmTools
                    .getDigestFromSigAlg(crmfreq.getHeader().getProtectionAlg().getAlgorithm().getId()));
        }
        // Set all protection parameters
        CmpPbeVerifyer verifyer = null;
        if (StringUtils.equals(authenticationModule.getName(), CmpConfiguration.AUTHMODULE_HMAC)) {
            final HMACAuthenticationModule hmacmodule = (HMACAuthenticationModule) authenticationModule;
            verifyer = hmacmodule.getCmpPbeVerifyer();
            final String pbeDigestAlg = verifyer.getOwfOid();
            final String pbeMacAlg = verifyer.getMacOid();
            final int pbeIterationCount = verifyer.getIterationCount();
            final String raSecret = verifyer.getLastUsedRaSecret();
            if (LOG.isDebugEnabled()) {
                LOG.debug("responseProt=" + this.responseProt + ", pbeDigestAlg=" + pbeDigestAlg
                        + ", pbeMacAlg=" + pbeMacAlg + ", keyId=" + keyId + ", raSecret="
                        + (raSecret == null ? "null" : "not null"));
            }

            if (StringUtils.equals(this.responseProt, "pbe")) {
                crmfreq.setPbeParameters(keyId, raSecret, pbeDigestAlg, pbeMacAlg, pbeIterationCount);
            }
        }
        try {
            try {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Creating new request with eeProfileId '" + eeProfileId + "', certProfileId '"
                            + certProfileId + "', caId '" + caId + "'");
                }
                resp = this.certificateRequestSession.processCertReq(this.admin, userdata, req,
                        org.ejbca.core.protocol.cmp.CmpResponseMessage.class);
            } catch (EndEntityExistsException e) {
                final String updateMsg = INTRES.getLocalizedMessage("cmp.erroradduserupdate", username);
                LOG.info(updateMsg);
                // Try again
                resp = this.certificateRequestSession.processCertReq(this.admin, userdata, req,
                        org.ejbca.core.protocol.cmp.CmpResponseMessage.class);
            }
        } catch (UserDoesntFullfillEndEntityProfile e) {
            LOG.info(INTRES.getLocalizedMessage(CMP_ERRORADDUSER, username), e);
            resp = CmpMessageHelper.createErrorMessage(msg, FailInfo.INCORRECT_DATA, e.getMessage(), requestId,
                    requestType, verifyer, keyId, this.responseProt);
        } catch (ApprovalException e) {
            LOG.info(INTRES.getLocalizedMessage(CMP_ERRORADDUSER, username), e);
            resp = CmpMessageHelper.createErrorMessage(msg, FailInfo.NOT_AUTHORIZED, e.getMessage(), requestId,
                    requestType, verifyer, keyId, this.responseProt);
        } catch (EndEntityExistsException e) {
            LOG.info(INTRES.getLocalizedMessage(CMP_ERRORADDUSER, username), e);
            resp = CmpMessageHelper.createErrorMessage(msg, FailInfo.NOT_AUTHORIZED, e.getMessage(), requestId,
                    requestType, verifyer, keyId, this.responseProt);
        } catch (CertificateExtensionException e) {
            LOG.info(INTRES.getLocalizedMessage(CMP_ERRORADDUSER, username), e);
            resp = CmpMessageHelper.createErrorMessage(msg, FailInfo.BAD_REQUEST, e.getMessage(), requestId,
                    requestType, verifyer, keyId, this.responseProt);
        }
    } catch (HandlerException e) {
        LOG.error(INTRES.getLocalizedMessage("cmp.errorexthandlerexec"), e);
        resp = CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE,
                FailInfo.BAD_MESSAGE_CHECK, e.getMessage());
    }
    return resp;
}

From source file:se.leap.bitmaskclient.ProviderAPI.java

private Bundle register(String username, String password) {
    LeapSRPSession client = new LeapSRPSession(username, password);
    byte[] salt = client.calculateNewSalt();

    BigInteger password_verifier = client.calculateV(username, password, salt);

    JSONObject api_result = sendNewUserDataToSRPServer(provider_api_url, username,
            new BigInteger(1, salt).toString(16), password_verifier.toString(16));

    Bundle result = new Bundle();
    if (api_result.has(ERRORS))
        result = authFailedNotification(api_result, username);
    else {/*  w w  w  .  ja  v  a  2s. c o m*/
        result.putString(SessionDialog.USERNAME, username);
        result.putString(SessionDialog.PASSWORD, password);
        result.putBoolean(RESULT_KEY, true);
    }

    return result;
}

From source file:org.broadleafcommerce.openadmin.server.dao.DynamicEntityDaoImpl.java

protected String getCacheKey(ForeignKey foreignField, String[] additionalNonPersistentProperties,
        ForeignKey[] additionalForeignFields, MergedPropertyType mergedPropertyType,
        Boolean populateManyToOneFields, Class<?> clazz, String configurationKey, Boolean isParentExcluded) {
    StringBuilder sb = new StringBuilder(150);
    sb.append(clazz.hashCode());/*www  .ja  v a 2s  .  c  o m*/
    sb.append(foreignField == null ? "" : foreignField.toString());
    sb.append(configurationKey);
    sb.append(isParentExcluded);
    if (additionalNonPersistentProperties != null) {
        for (String prop : additionalNonPersistentProperties) {
            sb.append(prop);
        }
    }
    if (additionalForeignFields != null) {
        for (ForeignKey key : additionalForeignFields) {
            sb.append(key.toString());
        }
    }
    sb.append(mergedPropertyType);
    sb.append(populateManyToOneFields);

    String digest;
    try {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] messageDigest = md.digest(sb.toString().getBytes());
        BigInteger number = new BigInteger(1, messageDigest);
        digest = number.toString(16);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }

    return pad(digest, 32, '0');
}

From source file:com.flexive.shared.FxSharedUtils.java

/**
 * Calculate an MD5 checksum for a file//from w  ww .j  a v a  2  s  . c  om
 *
 * @param file file to calculate checksum for
 * @return MD5 checksum (16 characters)
 */
public static String getMD5Sum(File file) {
    InputStream is = null;
    String md5sum = "unknown";
    try {
        MessageDigest digest = MessageDigest.getInstance("MD5");
        is = new FileInputStream(file);
        byte[] buffer = new byte[8192];
        int read;
        while ((read = is.read(buffer)) > 0)
            digest.update(buffer, 0, read);
        BigInteger bigInt = new BigInteger(1, digest.digest());
        md5sum = bigInt.toString(16);
    } catch (IOException e) {
        LOG.error("Unable calculate MD5 checksum!", e);
    } catch (NoSuchAlgorithmException e) {
        LOG.error("No MD5 algorithm found!", e);
    } finally {
        try {
            if (is != null)
                is.close();
        } catch (IOException e) {
            //ignore
        }
    }
    return md5sum;
}

From source file:com.google.bitcoin.core.Block.java

/** Returns true if the hash of the block is OK (lower than difficulty target). */
private boolean checkProofOfWork(boolean throwException) throws VerificationException {
    // This part is key - it is what proves the block was as difficult to make as it claims
    // to be. Note however that in the context of this function, the block can claim to be
    // as difficult as it wants to be .... if somebody was able to take control of our network
    // connection and fork us onto a different chain, they could send us valid blocks with
    // ridiculously easy difficulty and this function would accept them.
    ////from  ww  w.  j  ava 2  s  .  co m
    // To prevent this attack from being possible, elsewhere we check that the difficultyTarget
    // field is of the right value. This requires us to have the preceeding blocks.
    BigInteger target = getDifficultyTargetAsInteger();

    BigInteger h = getHash().toBigInteger();
    if (h.compareTo(target) > 0) {
        // Proof of work check failed!
        if (throwException)
            throw new VerificationException(
                    "Hash is higher than target: " + getHashAsString() + " vs " + target.toString(16));
        else
            return false;
    }
    return true;
}

From source file:net.sf.dsig.verify.OCSPHelper.java

/**
 * Check with OCSP protocol whether a certificate is valid
 * /*from   w w  w. java2 s  .c om*/
 * @param certificate an {@link X509Certificate} object
 * @return true if the certificate is valid; false otherwise
 * @throws NetworkAccessException when any network access issues occur
 * @throws VerificationException when an OCSP related error occurs
 */
public boolean isValid(X509Certificate certificate) throws NetworkAccessException, VerificationException {
    PostMethod post = null;

    try {
        CertificateID cid = new CertificateID(CertificateID.HASH_SHA1, caCertificate,
                certificate.getSerialNumber());

        OCSPReqGenerator gen = new OCSPReqGenerator();
        gen.addRequest(cid);

        // Nonce
        BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis());
        Vector oids = new Vector();
        Vector values = new Vector();
        oids.add(OCSPObjectIdentifiers.id_pkix_ocsp_nonce);
        values.add(new X509Extension(false, new DEROctetString(nonce.toByteArray())));
        values.add(new X509Extension(false,
                new DEROctetString(new BigInteger("041063FAB2B54CF1ED014F9DF7C70AACE575", 16).toByteArray())));
        gen.setRequestExtensions(new X509Extensions(oids, values));

        // Requestor name - not really required, but added for completeness
        //          gen.setRequestorName(
        //                  new GeneralName(
        //                          new X509Name(
        //                                  certificate.getSubjectX500Principal().getName())));

        logger.debug("Generating OCSP request" + "; serialNumber=" + certificate.getSerialNumber().toString(16)
                + ", nonce=" + nonce.toString(16) + ", caCertificate.subjectName="
                + caCertificate.getSubjectX500Principal().getName());

        // TODO Need to call the generate(...) method, that signs the 
        // request. Which means, need to have a keypair for that, too
        OCSPReq req = gen.generate();

        // First try finding the OCSP access location in the X.509 certificate
        String uriAsString = getOCSPAccessLocationUri(certificate);

        // If not found, try falling back to the default
        if (uriAsString == null) {
            uriAsString = defaultOcspAccessLocation;
        }

        // If still null, bail out
        if (uriAsString == null) {
            throw new ConfigurationException(
                    "OCSP AccessLocation not found on certificate, and no default set");
        }

        HostConfiguration config = getHostConfiguration();

        post = new PostMethod(uriAsString);
        post.setRequestHeader("Content-Type", "application/ocsp-request");
        post.setRequestHeader("Accept", "application/ocsp-response");
        post.setRequestEntity(new ByteArrayRequestEntity(req.getEncoded()));

        getHttpClient().executeMethod(config, post);

        logger.debug("HTTP POST executed" + "; authorityInfoAccessUri=" + uriAsString + ", statusLine="
                + post.getStatusLine());

        if (post.getStatusCode() != HttpStatus.SC_OK) {
            throw new NetworkAccessException("HTTP GET failed; statusLine=" + post.getStatusLine());
        }

        byte[] responseBodyBytes = post.getResponseBody();

        OCSPResp ocspRes = new OCSPResp(responseBodyBytes);
        if (ocspRes.getStatus() != OCSPResponseStatus.SUCCESSFUL) {
            // One possible exception is the use of a wrong CA certificate
            throw new ConfigurationException("OCSP request failed; possibly wrong issuer/user certificate"
                    + "; status=" + ocspRes.getStatus());
        }

        BasicOCSPResp res = (BasicOCSPResp) ocspRes.getResponseObject();
        SingleResp[] responses = res.getResponses();
        SingleResp response = responses[0];

        CertificateStatus status = (CertificateStatus) response.getCertStatus();
        // Normal OCSP protocol allows a null status
        return status == null || status == CertificateStatus.GOOD;
    } catch (IOException e) {
        throw new NetworkAccessException("I/O error occured", e);
    } catch (OCSPException e) {
        throw new VerificationException("Error while following OCSP protocol", e);
    } finally {
        if (post != null) {
            post.releaseConnection();
        }
    }
}

From source file:org.ejbca.ui.cmpclient.commands.CrmfRequestCommand.java

@Override
public PKIMessage generatePKIMessage(final ParameterContainer parameters) throws Exception {

    final boolean verbose = parameters.containsKey(VERBOSE_KEY);

    final X500Name userDN = new X500Name(parameters.get(SUBJECTDN_KEY));
    final X500Name issuerDN = new X500Name(parameters.get(ISSUERDN_KEY));

    String authmodule = parameters.get(AUTHENTICATION_MODULE_KEY);
    String endentityPassword = "";
    if (authmodule != null && StringUtils.equals(authmodule, CmpConfiguration.AUTHMODULE_REG_TOKEN_PWD)) {
        endentityPassword = parameters.containsKey(AUTHENTICATION_PARAM_KEY)
                ? parameters.get(AUTHENTICATION_PARAM_KEY)
                : "foo123";
    }/*from w ww.  ja va  2s  . c o m*/

    String altNames = parameters.get(ALTNAME_KEY);
    String serno = parameters.get(SERNO_KEY);
    BigInteger customCertSerno = null;
    if (serno != null) {
        customCertSerno = new BigInteger(serno, 16);
    }
    boolean includePopo = parameters.containsKey(INCLUDE_POPO_KEY);

    if (verbose) {
        log.info("Creating CRMF request with: SubjectDN=" + userDN.toString());
        log.info("Creating CRMF request with: IssuerDN=" + issuerDN.toString());
        log.info("Creating CRMF request with: AuthenticationModule=" + authmodule);
        log.info("Creating CRMF request with: EndEntityPassword=" + endentityPassword);
        log.info("Creating CRMF request with: SubjectAltName=" + altNames);
        log.info("Creating CRMF request with: CustomCertSerno="
                + (customCertSerno == null ? "" : customCertSerno.toString(16)));
        log.info("Creating CRMF request with: IncludePopo=" + includePopo);
    }

    final KeyPair keys = KeyTools.genKeys("1024", AlgorithmConstants.KEYALGORITHM_RSA);
    final byte[] nonce = CmpClientMessageHelper.getInstance().createSenderNonce();
    final byte[] transid = CmpClientMessageHelper.getInstance().createSenderNonce();

    // We should be able to back date the start time when allow validity
    // override is enabled in the certificate profile
    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.DAY_OF_WEEK, -1);
    cal.set(Calendar.MILLISECOND, 0); // Certificates don't use milliseconds
    // in validity
    Date notBefore = cal.getTime();
    cal.add(Calendar.DAY_OF_WEEK, 3);
    cal.set(Calendar.MILLISECOND, 0); // Certificates don't use milliseconds
    org.bouncycastle.asn1.x509.Time nb = new org.bouncycastle.asn1.x509.Time(notBefore);
    // in validity
    Date notAfter = cal.getTime();
    org.bouncycastle.asn1.x509.Time na = new org.bouncycastle.asn1.x509.Time(notAfter);

    ASN1EncodableVector optionalValidityV = new ASN1EncodableVector();
    optionalValidityV.add(new DERTaggedObject(true, 0, nb));
    optionalValidityV.add(new DERTaggedObject(true, 1, na));
    OptionalValidity myOptionalValidity = OptionalValidity.getInstance(new DERSequence(optionalValidityV));

    CertTemplateBuilder myCertTemplate = new CertTemplateBuilder();
    myCertTemplate.setValidity(myOptionalValidity);
    if (issuerDN != null) {
        myCertTemplate.setIssuer(issuerDN);
    }
    myCertTemplate.setSubject(userDN);
    byte[] bytes = keys.getPublic().getEncoded();
    ByteArrayInputStream bIn = new ByteArrayInputStream(bytes);
    ASN1InputStream dIn = new ASN1InputStream(bIn);
    SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo((ASN1Sequence) dIn.readObject());
    dIn.close();
    myCertTemplate.setPublicKey(keyInfo);

    // Create standard extensions
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    ASN1OutputStream dOut = new ASN1OutputStream(bOut);
    ExtensionsGenerator extgen = new ExtensionsGenerator();
    if (altNames != null) {
        GeneralNames san = CertTools.getGeneralNamesFromAltName(altNames);
        dOut.writeObject(san);
        byte[] value = bOut.toByteArray();
        extgen.addExtension(Extension.subjectAlternativeName, false, value);
    }

    // KeyUsage
    int bcku = 0;
    bcku = KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.nonRepudiation;
    KeyUsage ku = new KeyUsage(bcku);
    extgen.addExtension(Extension.keyUsage, false, new DERBitString(ku));

    // Make the complete extension package
    Extensions exts = extgen.generate();

    myCertTemplate.setExtensions(exts);
    if (customCertSerno != null) {
        // Add serialNumber to the certTemplate, it is defined as a MUST NOT be used in RFC4211, but we will use it anyway in order
        // to request a custom certificate serial number (something not standard anyway)
        myCertTemplate.setSerialNumber(new ASN1Integer(customCertSerno));
    }

    CertRequest myCertRequest = new CertRequest(4, myCertTemplate.build(), null);

    // POPO
    /*
     * PKMACValue myPKMACValue = new PKMACValue( new AlgorithmIdentifier(new
     * ASN1ObjectIdentifier("8.2.1.2.3.4"), new DERBitString(new byte[] { 8,
     * 1, 1, 2 })), new DERBitString(new byte[] { 12, 29, 37, 43 }));
     * 
     * POPOPrivKey myPOPOPrivKey = new POPOPrivKey(new DERBitString(new
     * byte[] { 44 }), 2); //take choice pos tag 2
     * 
     * POPOSigningKeyInput myPOPOSigningKeyInput = new POPOSigningKeyInput(
     * myPKMACValue, new SubjectPublicKeyInfo( new AlgorithmIdentifier(new
     * ASN1ObjectIdentifier("9.3.3.9.2.2"), new DERBitString(new byte[] { 2,
     * 9, 7, 3 })), new byte[] { 7, 7, 7, 4, 5, 6, 7, 7, 7 }));
     */
    ProofOfPossession myProofOfPossession = null;
    if (includePopo) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DEROutputStream mout = new DEROutputStream(baos);
        mout.writeObject(myCertRequest);
        mout.close();
        byte[] popoProtectionBytes = baos.toByteArray();
        String sigalg = AlgorithmTools.getSignAlgOidFromDigestAndKey(null, keys.getPrivate().getAlgorithm())
                .getId();
        Signature sig = Signature.getInstance(sigalg, "BC");
        sig.initSign(keys.getPrivate());
        sig.update(popoProtectionBytes);
        DERBitString bs = new DERBitString(sig.sign());
        POPOSigningKey myPOPOSigningKey = new POPOSigningKey(null,
                new AlgorithmIdentifier(new ASN1ObjectIdentifier(sigalg)), bs);
        myProofOfPossession = new ProofOfPossession(myPOPOSigningKey);
    } else {
        // raVerified POPO (meaning there is no POPO)
        myProofOfPossession = new ProofOfPossession();
    }

    AttributeTypeAndValue av = new AttributeTypeAndValue(CRMFObjectIdentifiers.id_regCtrl_regToken,
            new DERUTF8String(endentityPassword));
    AttributeTypeAndValue[] avs = { av };

    CertReqMsg myCertReqMsg = new CertReqMsg(myCertRequest, myProofOfPossession, avs);

    CertReqMessages myCertReqMessages = new CertReqMessages(myCertReqMsg);

    PKIHeaderBuilder myPKIHeader = new PKIHeaderBuilder(2, new GeneralName(userDN), new GeneralName(issuerDN));

    myPKIHeader.setMessageTime(new ASN1GeneralizedTime(new Date()));
    // senderNonce
    myPKIHeader.setSenderNonce(new DEROctetString(nonce));
    // TransactionId
    myPKIHeader.setTransactionID(new DEROctetString(transid));
    myPKIHeader.setProtectionAlg(null);
    myPKIHeader.setSenderKID(new byte[0]);

    PKIBody myPKIBody = new PKIBody(0, myCertReqMessages); // initialization
    // request
    PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody);

    return myPKIMessage;
}