Example usage for org.bouncycastle.asn1 ASN1InputStream readObject

List of usage examples for org.bouncycastle.asn1 ASN1InputStream readObject

Introduction

In this page you can find the example usage for org.bouncycastle.asn1 ASN1InputStream readObject.

Prototype

public ASN1Primitive readObject() throws IOException 

Source Link

Usage

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

License:Open Source License

@Override
public CommandResult handleCMPResponse(byte[] response, final ParameterContainer parameters) throws Exception {
    String dest = parameters.get(DESTINATION_KEY);
    if (dest == null) {
        dest = "dest";
        new File("./" + dest).mkdirs();
        log.info("Using default destination directory: ./dest/");
    }//from   ww w.ja v a2s.  co m

    PKIMessage respObject = null;
    ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(response));
    try {
        respObject = PKIMessage.getInstance(asn1InputStream.readObject());
    } finally {
        asn1InputStream.close();
    }
    if (respObject == null) {
        log.error("ERROR. Cannot construct the response object");
        return CommandResult.FUNCTIONAL_FAILURE;
    }

    PKIBody body = respObject.getBody();
    int tag = body.getType();

    if (tag == PKIBody.TYPE_INIT_REP) {
        CertRepMessage c = (CertRepMessage) body.getContent();
        CertResponse resp = c.getResponse()[0];
        PKIStatusInfo status = resp.getStatus();
        if (status.getStatus().intValue() == PKIStatus.GRANTED) {
            final X509Certificate cert = getCertFromResponse(resp);
            final ArrayList<Certificate> certs = new ArrayList<>();
            certs.add(cert);
            final byte[] certBytes = CertTools.getPemFromCertificateChain(certs);

            String certFileName = getDestinationCertFile(dest, parameters.get(SUBJECTDN_KEY));
            final FileOutputStream fos = new FileOutputStream(new File(certFileName));
            fos.write(certBytes);
            fos.close();
            log.info("CRMF request successful. Received certificate stored in " + certFileName);
            return CommandResult.SUCCESS;
        } else {
            final String errMsg = status.getStatusString().getStringAt(0).getString();
            log.error("Recieved CRMF response with status '" + status.getStatus().intValue()
                    + "' and error message: " + errMsg);
        }
    } else if (tag == PKIBody.TYPE_ERROR) {
        ErrorMsgContent err = (ErrorMsgContent) body.getContent();
        final String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString();
        log.error("Revceived CMP Error Message: " + errMsg);
    } else {
        log.error("Received PKIMessage with body tag " + tag);
    }
    return CommandResult.FUNCTIONAL_FAILURE;
}

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

License:Open Source License

@Override
public PKIMessage generatePKIMessage(ParameterContainer parameters) throws Exception {
    boolean verbose = parameters.containsKey(VERBOSE_KEY);

    final X500Name userDN = new X500Name(parameters.get(SUBJECTDN_KEY));
    final X500Name issuerDN = new X500Name(parameters.get(ISSUERDN_KEY));
    boolean includePopo = parameters.containsKey(INCLUDE_POPO_KEY);

    if (verbose) {
        log.info("Creating KeyUpdate request with: SubjectDN=" + userDN.toString());
        log.info("Creating KeyUpdate request with: IssuerDN=" + issuerDN.toString());
        log.info("Creating KeyUpdate request with: IncludePopo=" + includePopo);
    }// w  ww  .  j av a2  s.  c  o  m

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

    CertTemplateBuilder myCertTemplate = new CertTemplateBuilder();

    ASN1EncodableVector optionalValidityV = new ASN1EncodableVector();
    org.bouncycastle.asn1.x509.Time nb = new org.bouncycastle.asn1.x509.Time(
            new DERGeneralizedTime("20030211002120Z"));
    org.bouncycastle.asn1.x509.Time na = new org.bouncycastle.asn1.x509.Time(new Date());
    optionalValidityV.add(new DERTaggedObject(true, 0, nb));
    optionalValidityV.add(new DERTaggedObject(true, 1, na));
    OptionalValidity myOptionalValidity = OptionalValidity.getInstance(new DERSequence(optionalValidityV));

    myCertTemplate.setValidity(myOptionalValidity);

    byte[] bytes = keys.getPublic().getEncoded();
    ByteArrayInputStream bIn = new ByteArrayInputStream(bytes);
    ASN1InputStream dIn = new ASN1InputStream(bIn);
    try {
        SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo((ASN1Sequence) dIn.readObject());
        myCertTemplate.setPublicKey(keyInfo);
    } finally {
        dIn.close();
    }

    myCertTemplate.setSubject(userDN);

    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);
        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();
    }

    // myCertReqMsg.addRegInfo(new AttributeTypeAndValue(new
    // ASN1ObjectIdentifier("1.3.6.2.2.2.2.3.1"), new
    // DERInteger(1122334455)));
    AttributeTypeAndValue av = new AttributeTypeAndValue(CRMFObjectIdentifiers.id_regCtrl_regToken,
            new DERUTF8String(""));
    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);

    PKIBody myPKIBody = new PKIBody(PKIBody.TYPE_KEY_UPDATE_REQ, myCertReqMessages); // Key Update Request
    PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody);

    return myPKIMessage;
}

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

License:Open Source License

@Override
public CommandResult handleCMPResponse(byte[] response, ParameterContainer parameters) throws Exception {
    String dest = parameters.get(DESTINATION_KEY);
    if (dest == null) {
        dest = "dest";
        new File("./" + dest).mkdirs();
        log.info("Using default destination directory: ./dest/");
    }//w  ww .  j a  v a  2 s.co m

    PKIMessage respObject = null;
    ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(response));
    try {
        respObject = PKIMessage.getInstance(asn1InputStream.readObject());
    } finally {
        asn1InputStream.close();
    }
    if (respObject == null) {
        log.error("Cannot construct response object");
        return CommandResult.FUNCTIONAL_FAILURE;
    }

    PKIBody body = respObject.getBody();
    int tag = body.getType();
    if (tag == PKIBody.TYPE_KEY_UPDATE_REP) {
        CertRepMessage c = (CertRepMessage) body.getContent();
        CertResponse resp = c.getResponse()[0];
        PKIStatusInfo status = resp.getStatus();

        if (status.getStatus().intValue() == PKIStatus.GRANTED) {
            final X509Certificate cert = getCertFromResponse(resp);
            final ArrayList<Certificate> certs = new ArrayList<>();
            certs.add(cert);
            final byte[] certBytes = CertTools.getPemFromCertificateChain(certs);

            String certFileName = getDestinationCertFile(dest, parameters.get(SUBJECTDN_KEY));
            final FileOutputStream fos = new FileOutputStream(new File(certFileName));
            fos.write(certBytes);
            fos.close();
            log.info("CRMF request successful. Received certificate stored in " + certFileName);
            return CommandResult.SUCCESS;
        } else {
            final String errMsg = status.getStatusString().getStringAt(0).getString();
            log.error("Recieved CRMF response with status '" + status.getStatus().intValue()
                    + "' and error message: " + errMsg);
        }

    } else if (tag == PKIBody.TYPE_ERROR) {
        log.error("Error response was recieved");
        ErrorMsgContent c = (ErrorMsgContent) body.getContent();
        PKIStatusInfo info = c.getPKIStatusInfo();
        log.error("Error message: " + info.getStatusString().getStringAt(0));
    } else {
        log.error("Recieved response with body type(See PKIBody.java): " + tag);
    }
    return CommandResult.FUNCTIONAL_FAILURE;
}

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

License:Open Source License

@Override
public CommandResult handleCMPResponse(byte[] response, ParameterContainer parameters) throws Exception {
    PKIMessage respObject = null;/*from  w  w w  .ja v  a  2  s. c  o m*/
    ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(response));
    try {
        respObject = PKIMessage.getInstance(asn1InputStream.readObject());
    } finally {
        asn1InputStream.close();
    }
    if (respObject == null) {
        log.error("Cannot construct response object");
        return CommandResult.FUNCTIONAL_FAILURE;
    }

    PKIBody body = respObject.getBody();
    int tag = body.getType();
    if (tag == PKIBody.TYPE_REVOCATION_REP) {
        log.info("Revocation response was recieved");
        RevRepContent n = (RevRepContent) body.getContent();
        PKIStatusInfo info = n.getStatus()[0];
        if (info.getStatus().intValue() == 0) {
            log.info("Revocation request have succeeded");
            return CommandResult.SUCCESS;
        } else {
            log.error("Revocation request failed with status (See PKIStatusInfo.java): "
                    + info.getStatus().intValue());
        }
    } else if (tag == PKIBody.TYPE_ERROR) {
        log.error("Error response was recieved");
        ErrorMsgContent c = (ErrorMsgContent) body.getContent();
        PKIStatusInfo info = c.getPKIStatusInfo();
        log.error("Error message: " + info.getStatusString().getStringAt(0).getString());
    } else {
        log.error("Recieved response with body type(See PKIBody.java): " + tag);
    }
    return CommandResult.FUNCTIONAL_FAILURE;
}

From source file:org.ejbca.ui.web.pub.inspect.CertAndRequestDumpBean.java

License:Open Source License

/** Dumps contents, and updates "type" variable as side-effect.
 * //from  w ww . jav  a 2 s .c  om
 * @return String containing raw text output or null of input is null, or error message if input invalid.
 */
public String getDump() {
    String ret = null;
    if (bytes == null) {
        return null;
    }
    final byte[] requestBytes = RequestMessageUtils.getDecodedBytes(bytes);
    ret = getCvcDump(false);
    if ((ret == null) && (requestBytes != null) && (requestBytes.length > 0)) {
        // Not a CVC request, perhaps a PKCS10 request
        try {
            final PKCS10CertificationRequest pkcs10 = new PKCS10CertificationRequest(requestBytes);
            //            ret = pkcs10.toString();
            final ASN1InputStream ais = new ASN1InputStream(new ByteArrayInputStream(pkcs10.getEncoded()));
            final ASN1Primitive obj = ais.readObject();
            ais.close();
            ret = ASN1Dump.dumpAsString(obj);
            type = "PKCS#10";
        } catch (IOException e1) {
            // ignore, move on to certificate decoding
        } catch (IllegalArgumentException e1) {
            // ignore, move on to certificate decoding
        } catch (ClassCastException e2) {
            // ignore, move on to certificate decoding
        }
    } else if (ret != null) {
        type = "CVC";
    }
    if (ret == null) {
        // Not a CVC object or PKCS10 request message, perhaps a X.509 certificate?
        try {
            final Certificate cert = getCert(bytes);
            ret = CertTools.dumpCertificateAsString(cert);
            type = "X.509";
        } catch (Exception e) {
            // Not a X.509 certificate either...try to simply decode asn.1
            try {
                final ASN1InputStream ais = new ASN1InputStream(new ByteArrayInputStream(bytes));
                final ASN1Primitive obj = ais.readObject();
                ais.close();
                if (obj != null) {
                    ret = ASN1Dump.dumpAsString(obj);
                    type = "ASN.1";
                }
            } catch (IOException e1) {
                // Last stop, say what the error is
                ret = e1.getMessage();
            }
        }
    }
    return ret;
}

From source file:org.ejbca.ui.web.RequestHelper.java

License:Open Source License

/**
 * Handles Firefox certificate request (KEYGEN), these are constructed as: <code>
 * SignedPublicKeyAndChallenge ::= SEQUENCE { publicKeyAndChallenge    PublicKeyAndChallenge,
 * signatureAlgorithm   AlgorithmIdentifier, signature        BIT STRING }</code> PublicKey's
 * encoded-format has to be RSA X.509.//  ww w  . java2  s.co  m
 *
 * @param signsession EJB session to signature bean.
 * @param reqBytes buffer holding te request from NS.
 * @param username username in EJBCA for authoriation.
 * @param password users password for authorization.
 *
 * @return byte[] containing DER-encoded certificate.
 *
 * @throws CesecoreException 
 * @throws AuthorizationDeniedException 
 * @throws EjbcaException 
 * @throws CADoesntExistsException 
 * @throws ObjectNotFoundException 
 * @throws CertificateEncodingException 
 * @throws NoSuchProviderException 
 * @throws SignatureException 
 * @throws NoSuchAlgorithmException 
 * @throws InvalidKeyException 
 */
public byte[] nsCertRequest(SignSessionLocal signsession, byte[] reqBytes, String username, String password)
        throws ObjectNotFoundException, CADoesntExistsException, EjbcaException, AuthorizationDeniedException,
        CesecoreException, CertificateEncodingException, InvalidKeyException, NoSuchAlgorithmException,
        SignatureException, NoSuchProviderException {
    byte[] buffer = Base64.decode(reqBytes);

    if (buffer == null) {
        return null;
    }

    ASN1InputStream in = new ASN1InputStream(new ByteArrayInputStream(buffer));
    ASN1Sequence spkac;
    try {
        spkac = (ASN1Sequence) in.readObject();
        in.close();
    } catch (IOException e) {
        throw new IllegalStateException("Unexpected IOException was caught.", e);
    }

    NetscapeCertRequest nscr = new NetscapeCertRequest(spkac);

    // Verify POPO, we don't care about the challenge, it's not important.
    nscr.setChallenge("challenge");

    if (nscr.verify("challenge") == false) {
        throw new SignRequestSignatureException(
                "Invalid signature in NetscapeCertRequest, popo-verification failed.");
    }
    if (log.isDebugEnabled()) {
        log.debug("POPO verification successful");
    }
    X509Certificate cert = (X509Certificate) signsession.createCertificate(administrator, username, password,
            nscr.getPublicKey());
    if (log.isDebugEnabled()) {
        log.debug("Created certificate for " + username);
    }
    if (debug != null) {
        debug.print("<h4>Generated certificate:</h4>");
        debug.printInsertLineBreaks(cert.toString().getBytes());
    }
    return cert.getEncoded();

    /* ECA-2065: the <keygen> specification doesn't say anything about the
     * returned certificate.  Originally EJBCA used a PKCS7 container but
     * this has proved to be incompatible with Safari and Chrome.  ECA-2065
     * changes returned data to just a DER-encoded certificate which has
     * been verified to work in Firefox, Chrome and Safari.  The mime-type
     * remains application/x-x509-user-certificate.  Below is the deleted
     * code: 
            // Don't include certificate chain in the PKCS7 to Firefox
            byte[] pkcs7 = signsession.createPKCS7(administrator, cert, false);
            log.debug("Created certificate (PKCS7) for " + username);
            if (debug != null) {
    debug.print("<h4>Generated certificate:</h4>");
    debug.printInsertLineBreaks(cert.toString().getBytes());
            }
            
            return pkcs7;
    */
}

From source file:org.ejbca.util.cert.CrlExtensions.java

License:Open Source License

/**
 * Return an Extension DERObject from a CRL
 *//* w  ww.  j av a  2 s .c o  m*/
protected static DERObject getExtensionValue(X509CRL crl, String oid) throws IOException {
    if (crl == null) {
        return null;
    }
    byte[] bytes = crl.getExtensionValue(oid);
    if (bytes == null) {
        return null;
    }
    ASN1InputStream aIn = new ASN1InputStream(new ByteArrayInputStream(bytes));
    ASN1OctetString octs = (ASN1OctetString) aIn.readObject();
    aIn = new ASN1InputStream(new ByteArrayInputStream(octs.getOctets()));
    return aIn.readObject();
}

From source file:org.ejbca.util.CertTools.java

License:Open Source License

/** Gets an altName string from an X509Extension
 * //from  w ww  .j  a  v a  2s.  c  o  m
 * @param ext X509Extension with AlternativeNames
 * @return String as defined in method getSubjectAlternativeName
 */
public static String getAltNameStringFromExtension(X509Extension ext) {
    String altName = null;
    //GeneralNames
    ASN1OctetString octs = ext.getValue();
    if (octs != null) {
        ASN1InputStream aIn = new ASN1InputStream(new ByteArrayInputStream(octs.getOctets()));
        DERObject obj;
        try {
            obj = aIn.readObject();
            GeneralNames gan = GeneralNames.getInstance(obj);
            GeneralName[] gns = gan.getNames();
            for (int i = 0; i < gns.length; i++) {
                GeneralName gn = gns[i];
                int tag = gn.getTagNo();
                DEREncodable name = gn.getName();
                String str = CertTools.getGeneralNameString(tag, name);
                if (altName == null) {
                    altName = str;
                } else {
                    altName += ", " + str;
                }
            }
        } catch (IOException e) {
            log.error("IOException parsing altNames: ", e);
            return null;
        }
    }
    return altName;
}

From source file:org.ejbca.util.CertTools.java

License:Open Source License

/**
 * Return an Extension DERObject from a certificate
 *///from  w w w.ja  v a2 s  .c  o  m
protected static DERObject getExtensionValue(X509Certificate cert, String oid) throws IOException {
    if (cert == null) {
        return null;
    }
    byte[] bytes = cert.getExtensionValue(oid);
    if (bytes == null) {
        return null;
    }
    ASN1InputStream aIn = new ASN1InputStream(new ByteArrayInputStream(bytes));
    ASN1OctetString octs = (ASN1OctetString) aIn.readObject();
    aIn = new ASN1InputStream(new ByteArrayInputStream(octs.getOctets()));
    return aIn.readObject();
}

From source file:org.glite.security.delegation.GrDProxyGenerator.java

License:Apache License

/**
 * Creates a proxy certificate from a certificate request
 * //from w ww.  ja  v a  2s . c o m
 * @param inCertReq
 *            Certificate request
 * @param inUserCert
 *            Issuer certificate
 * @param inUserKey
 *            Issuer privateKey
 * @param pwd
 *            Issuer password
 * @return chaine of certificate containing proxy in first place
 * @deprecated Use proxy generator from util-java
 */
public byte[] x509MakeProxyCert(byte[] inCertReq, byte[] inUserCert, byte[] inUserKey, String pwd1)
        throws CertificateException, GeneralSecurityException, Exception {
    X509Certificate[] userCert = null;
    PrivateKey pvk = null;

    // Read certificate request
    InputStream inTCertReq = null;

    inTCertReq = new ByteArrayInputStream(
            GrDPX509Util.readPEM(new ByteArrayInputStream(inCertReq), GrDPConstants.CRH, GrDPConstants.CRF));

    if ((inUserCert != null) && (inUserKey != null)) {
        // Reading chain of certificates from input stream
        userCert = GrDPX509Util
                .loadCertificateChain(new BufferedInputStream(new ByteArrayInputStream(inUserCert)));

        if (userCert.length <= 0) {
            logger.error("Invalid user certificate. Number of certificates in chain : " + userCert.length);
            throw new GeneralSecurityException("Invalid user certificate.");
        }

        pvk = PrivateKeyReader.read(new BufferedInputStream(new ByteArrayInputStream(inUserKey)), pwd1);
    } else {
        logger.error("Error, CreateProxyFromCertReq :: UserCertificate and UserKey can not be null.");
        throw new CertificateException(
                "Error, CreateProxyFromCertReq :: UserCertificate and UserKey can not be null.");
    }

    // Loading chian of certificates
    X509Certificate[] cp = new X509Certificate[userCert.length + 1];

    ASN1InputStream derin = new ASN1InputStream(inTCertReq);
    DERObject reqInfo = derin.readObject();
    PKCS10CertificationRequest certReq = new PKCS10CertificationRequest((DERSequence) reqInfo);
    logger.debug("Number of Certificates in chain : " + Integer.toString(userCert.length));

    if (!certReq.verify()) {
        throw new GeneralSecurityException("Certificate request verification failed!");
    }

    // Generating proxy certificate
    cp[0] = createProxyCertificate(userCert[0], pvk, certReq.getPublicKey(), lifetime, proxyType, "proxy");

    for (int index = 1; index <= userCert.length; ++index)
        cp[index] = userCert[index - 1];

    certProxy = cp[0];

    return GrDPX509Util.certChainToByte(cp);
}