Example usage for org.bouncycastle.asn1 ASN1Integer getValue

List of usage examples for org.bouncycastle.asn1 ASN1Integer getValue

Introduction

In this page you can find the example usage for org.bouncycastle.asn1 ASN1Integer getValue.

Prototype

public BigInteger getValue() 

Source Link

Usage

From source file:org.demoiselle.signer.policy.engine.asn1.etsi.AlgAndLength.java

License:Open Source License

@Override
public void parse(ASN1Primitive derObject) {
    ASN1Sequence derSequence = ASN1Object.getDERSequence(derObject);
    this.algID = new ObjectIdentifier();
    this.algID.parse(derSequence.getObjectAt(0).toASN1Primitive());
    if (derSequence.size() >= 2) {
        ASN1Integer derInteger = (ASN1Integer) derSequence.getObjectAt(1).toASN1Primitive();
        this.setMinKeyLength(derInteger.getValue().intValue());
    }/*w w w.  j a va2s . com*/
    if (derSequence.size() == 3) {
        this.other = new SignPolExtensions();
        this.other.parse(derSequence.getObjectAt(2).toASN1Primitive());
    }
}

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

License:Open Source License

/** Gets a requested certificate serial number of the subject. This is a standard field in the CertTemplate in the request.
 * However the standard RFC 4211, section 5 (CertRequest syntax) says it MUST not be used. 
 * Requesting custom certificate serial numbers is a very non-standard procedure anyhow, so we use it anyway. 
 * /*  ww w  . j a  va  2  s.c o m*/
 * @return BigInteger the requested custom certificate serial number or null, normally this should return null.
 */
public BigInteger getSubjectCertSerialNo() {
    BigInteger ret = null;
    final CertRequest request = getReq().getCertReq();
    final CertTemplate templ = request.getCertTemplate();
    final ASN1Integer serno = templ.getSerialNumber();
    if (serno != null) {
        ret = serno.getValue();
    }
    return ret;
}

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

License:Open Source License

public GeneralCmpMessage(final PKIMessage msg) {
    final PKIBody body = msg.getBody();
    final int tag = body.getType();
    if (tag == 19) {
        // this is a PKIConfirmContent
        if (log.isDebugEnabled()) {
            log.debug("Received a PKIConfirm message");
        }/*from  w w w .  ja  va2  s .  c o  m*/
        // This is a null message, so there is nothing to get here
        //DERNull obj = body.getConf();
    }
    if (tag == 24) {
        // this is a CertConfirmContent
        if (log.isDebugEnabled()) {
            log.debug("Received a Cert Confirm message");
        }
        final CertConfirmContent obj = (CertConfirmContent) body.getContent();
        CertStatus cs;
        try {
            cs = CertStatus.getInstance(obj.toASN1Primitive());
        } catch (Exception e) {
            cs = CertStatus.getInstance(((DERSequence) obj.toASN1Primitive()).getObjectAt(0));
        }
        final PKIStatusInfo status = cs.getStatusInfo();
        if (status != null) {
            final int st = status.getStatus().intValue();
            if (st != 0) {
                final String errMsg = intres.getLocalizedMessage("cmp.errorcertconfirmstatus",
                        Integer.valueOf(st));
                log.error(errMsg);
                // TODO: if it is rejected, we should revoke the cert?
            }
        }
    }
    if (tag == 11) {
        // this is a RevReqContent,
        if (log.isDebugEnabled()) {
            log.debug("Received a RevReqContent");
        }
        final RevReqContent rr = (RevReqContent) body.getContent();
        RevDetails rd;
        try {
            rd = rr.toRevDetailsArray()[0];
        } catch (Exception e) {
            log.debug(
                    "Could not parse the revocation request. Trying to parse it as novosec generated message.");
            rd = CmpMessageHelper.getNovosecRevDetails(rr);
            log.debug("Succeeded in parsing the novosec generated request.");
        }
        final CertTemplate ct = rd.getCertDetails();
        final ASN1Integer serno = ct.getSerialNumber();
        final X500Name issuer = ct.getIssuer();
        if ((serno != null) && (issuer != null)) {
            final String errMsg = intres.getLocalizedMessage("cmp.receivedrevreq", issuer.toString(),
                    serno.getValue().toString(16));
            log.info(errMsg);
        } else {
            final String errMsg = intres.getLocalizedMessage("cmp.receivedrevreqnoissuer");
            log.info(errMsg);
        }
    }
    setMessage(msg);
    final PKIHeader header = msg.getHeader();
    if (header.getTransactionID() != null) {
        final byte[] val = header.getTransactionID().getOctets();
        if (val != null) {
            setTransactionId(new String(Base64.encode(val)));
        }
    }
    if (header.getSenderNonce() != null) {
        final byte[] val = header.getSenderNonce().getOctets();
        if (val != null) {
            setSenderNonce(new String(Base64.encode(val)));
        }
    }
    setRecipient(header.getRecipient());
    setSender(header.getSender());
}

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

License:Open Source License

public ResponseMessage handleMessage(final BaseCmpMessage msg, boolean authenticated) {
    if (LOG.isTraceEnabled()) {
        LOG.trace(">handleMessage");
    }// w ww  .j  a v  a2s. c o m

    CA ca = null;
    try {
        final String caDN = msg.getHeader().getRecipient().getName().toString();
        final int caId = CertTools.stringToBCDNString(caDN).hashCode();
        if (LOG.isDebugEnabled()) {
            LOG.debug("CA DN is '" + caDN + "' and resulting caId is " + caId
                    + ", after CertTools.stringToBCDNString conversion.");
        }
        ca = caSession.getCA(admin, caId);
    } catch (CADoesntExistsException e) {
        final String errMsg = "CA with DN '" + msg.getHeader().getRecipient().getName().toString()
                + "' is unknown";
        LOG.info(errMsg);
        return CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.BAD_REQUEST,
                errMsg);
    } catch (AuthorizationDeniedException e) {
        LOG.info(INTRES.getLocalizedMessage(CMP_ERRORGENERAL, e.getMessage()), e);
        return CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE,
                FailInfo.INCORRECT_DATA, e.getMessage());
    }

    ResponseMessage resp = null;
    // if version == 1 it is cmp1999 and we should not return a message back
    // Try to find a HMAC/SHA1 protection key
    final String keyId = CmpMessageHelper.getStringFromOctets(msg.getHeader().getSenderKID());
    ResponseStatus status = ResponseStatus.FAILURE;
    FailInfo failInfo = FailInfo.BAD_MESSAGE_CHECK;
    String failText = null;

    //Verify the authenticity of the message
    final VerifyPKIMessage messageVerifyer = new VerifyPKIMessage(ca.getCAInfo(), this.confAlias, admin,
            caSession, endEntityAccessSession, certificateStoreSession, authorizationSession,
            endEntityProfileSession, authenticationProviderSession, endEntityManagementSession,
            this.cmpConfiguration);
    ICMPAuthenticationModule authenticationModule = messageVerifyer
            .getUsedAuthenticationModule(msg.getMessage(), null, authenticated);
    if (authenticationModule == null) {
        LOG.info(messageVerifyer.getErrorMessage());
        return CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE,
                FailInfo.BAD_MESSAGE_CHECK, messageVerifyer.getErrorMessage());
    }

    // If authentication was correct, we will now try to find the certificate to revoke
    final PKIMessage pkimsg = msg.getMessage();
    final PKIBody body = pkimsg.getBody();
    final RevReqContent rr = (RevReqContent) body.getContent();
    RevDetails rd;
    try {
        rd = rr.toRevDetailsArray()[0];
    } catch (Exception e) {
        LOG.debug("Could not parse the revocation request. Trying to parse it as novosec generated message.");
        rd = CmpMessageHelper.getNovosecRevDetails(rr);
        LOG.debug("Succeeded in parsing the novosec generated request.");
    }
    final CertTemplate ct = rd.getCertDetails();
    final ASN1Integer serno = ct.getSerialNumber();
    final X500Name issuer = ct.getIssuer();
    // Get the revocation reason. 
    // For CMPv1 this can be a simple DERBitString or it can be a requested CRL Entry Extension
    // If there exists CRL Entry Extensions we will use that, because it's the only thing allowed in CMPv2
    int reason = RevokedCertInfo.REVOCATION_REASON_UNSPECIFIED;
    final ASN1OctetString reasonoctets = rd.getCrlEntryDetails().getExtension(Extension.reasonCode)
            .getExtnValue();
    DERBitString reasonbits;
    try {
        reasonbits = new DERBitString(reasonoctets.getEncoded());
    } catch (IOException e1) {
        LOG.info(INTRES.getLocalizedMessage(CMP_ERRORGENERAL, e1.getMessage()), e1);
        return CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE,
                FailInfo.INCORRECT_DATA, e1.getMessage());
    }
    if (reasonbits != null) {
        reason = CertTools.bitStringToRevokedCertInfo(reasonbits);
        if (LOG.isDebugEnabled()) {
            LOG.debug("CMPv1 revocation reason: " + reason);
        }
    }
    final Extensions crlExt = rd.getCrlEntryDetails();
    if (crlExt != null) {
        final Extension ext = crlExt.getExtension(Extension.reasonCode);
        if (ext != null) {
            try {
                final ASN1InputStream ai = new ASN1InputStream(ext.getExtnValue().getOctets());
                final ASN1Primitive obj = ai.readObject();
                final ASN1Enumerated crlreason = ASN1Enumerated.getInstance(obj);
                // RevokedCertInfo.REVOCATION_REASON_AACOMPROMISE are the same integer values as the CRL reason extension code
                reason = crlreason.getValue().intValue();
                if (LOG.isDebugEnabled()) {
                    LOG.debug("CRLReason extension: " + reason);
                }
                ai.close();
            } catch (IOException e) {
                LOG.info("Exception parsin CRL reason extension: ", e);
            }
        } else {
            if (LOG.isDebugEnabled()) {
                LOG.debug("No CRL reason code extension present.");
            }
        }
    } else {
        if (LOG.isDebugEnabled()) {
            LOG.debug("No CRL entry extensions present");
        }
    }

    if ((serno != null) && (issuer != null)) {
        final String iMsg = INTRES.getLocalizedMessage("cmp.receivedrevreq", issuer.toString(),
                serno.getValue().toString(16));
        LOG.info(iMsg);
        try {
            endEntityManagementSession.revokeCert(admin, serno.getValue(), issuer.toString(), reason);
            status = ResponseStatus.SUCCESS;
        } catch (AuthorizationDeniedException e) {
            failInfo = FailInfo.NOT_AUTHORIZED;
            final String errMsg = INTRES.getLocalizedMessage("cmp.errornotauthrevoke", issuer.toString(),
                    serno.getValue().toString(16));
            failText = errMsg;
            LOG.info(failText);
        } catch (FinderException e) {
            failInfo = FailInfo.BAD_CERTIFICATE_ID;
            final String errMsg = INTRES.getLocalizedMessage("cmp.errorcertnofound", issuer.toString(),
                    serno.getValue().toString(16));
            failText = errMsg;
            // This is already info logged in endEntityManagementSession.revokeCert
            // LOG.info(failText);
        } catch (WaitingForApprovalException e) {
            status = ResponseStatus.GRANTED_WITH_MODS;
        } catch (ApprovalException e) {
            failInfo = FailInfo.BAD_REQUEST;
            final String errMsg = INTRES.getLocalizedMessage("cmp.erroralreadyrequested");
            failText = errMsg;
            LOG.info(failText);
        } catch (AlreadyRevokedException e) {
            failInfo = FailInfo.BAD_REQUEST;
            final String errMsg = INTRES.getLocalizedMessage("cmp.erroralreadyrevoked");
            failText = errMsg;
            // This is already info logged in endEntityManagementSession.revokeCert
            // LOG.info(failText);
        }
    } else {
        failInfo = FailInfo.BAD_CERTIFICATE_ID;
        final String errMsg = INTRES.getLocalizedMessage("cmp.errormissingissuerrevoke", issuer.toString(),
                serno.getValue().toString(16));
        failText = errMsg;
        LOG.info(failText);
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Creating a PKI revocation message response");
    }
    final CmpRevokeResponseMessage rresp = new CmpRevokeResponseMessage();
    rresp.setRecipientNonce(msg.getSenderNonce());
    rresp.setSenderNonce(new String(Base64.encode(CmpMessageHelper.createSenderNonce())));
    rresp.setSender(msg.getRecipient());
    rresp.setRecipient(msg.getSender());
    rresp.setTransactionId(msg.getTransactionId());
    rresp.setFailInfo(failInfo);
    rresp.setFailText(failText);
    rresp.setStatus(status);

    if (StringUtils.equals(responseProtection, "pbe")) {
        final HMACAuthenticationModule hmacmodule = (HMACAuthenticationModule) authenticationModule;
        final String owfAlg = hmacmodule.getCmpPbeVerifyer().getOwfOid();
        final String macAlg = hmacmodule.getCmpPbeVerifyer().getMacOid();
        final int iterationCount = 1024;
        final String cmpRaAuthSecret = hmacmodule.getAuthenticationString();

        if ((owfAlg != null) && (macAlg != null) && (keyId != null) && (cmpRaAuthSecret != null)) {
            // Set all protection parameters
            if (LOG.isDebugEnabled()) {
                LOG.debug(responseProtection + ", " + owfAlg + ", " + macAlg + ", " + keyId + ", "
                        + cmpRaAuthSecret);
            }
            rresp.setPbeParameters(keyId, cmpRaAuthSecret, owfAlg, macAlg, iterationCount);
        }
    } else if (StringUtils.equals(responseProtection, "signature")) {
        try {
            final CryptoToken cryptoToken = cryptoTokenSession
                    .getCryptoToken(ca.getCAToken().getCryptoTokenId());
            final String aliasCertSign = ca.getCAToken()
                    .getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN);
            rresp.setSignKeyInfo(ca.getCertificateChain(), cryptoToken.getPrivateKey(aliasCertSign),
                    cryptoToken.getSignProviderName());
            if (msg.getHeader().getProtectionAlg() != null) {
                rresp.setPreferredDigestAlg(AlgorithmTools
                        .getDigestFromSigAlg(msg.getHeader().getProtectionAlg().getAlgorithm().getId()));
            }
        } catch (CryptoTokenOfflineException e) {
            LOG.error(e.getLocalizedMessage(), e);
        }
    }
    resp = rresp;
    try {
        resp.create();
    } catch (InvalidKeyException e) {
        String errMsg = INTRES.getLocalizedMessage("cmp.errorgeneral");
        LOG.error(errMsg, e);
    } catch (NoSuchAlgorithmException e) {
        String errMsg = INTRES.getLocalizedMessage("cmp.errorgeneral");
        LOG.error(errMsg, e);
    } catch (NoSuchProviderException e) {
        String errMsg = INTRES.getLocalizedMessage("cmp.errorgeneral");
        LOG.error(errMsg, e);
    } catch (CertificateEncodingException e) {
        String errMsg = INTRES.getLocalizedMessage("cmp.errorgeneral");
        LOG.error(errMsg, e);
    } catch (CRLException e) {
        String errMsg = INTRES.getLocalizedMessage("cmp.errorgeneral");
        LOG.error(errMsg, e);
    }

    return resp;
}

From source file:org.jmrtd.lds.SecurityInfo.java

License:Open Source License

/**
 * Factory method for creating security info objects given an input.
 *
 * @param obj the input/*from  w w  w.  j  av  a 2s  . co  m*/
 *
 * @return a concrete security info object
 */
public static SecurityInfo getInstance(ASN1Primitive obj) {
    try {
        ASN1Sequence sequence = (ASN1Sequence) obj;
        String oid = ((ASN1ObjectIdentifier) sequence.getObjectAt(0)).getId();
        ASN1Primitive requiredData = sequence.getObjectAt(1).toASN1Primitive();
        ASN1Primitive optionalData = null;
        if (sequence.size() == 3) {
            optionalData = sequence.getObjectAt(2).toASN1Primitive();
        }

        if (ActiveAuthenticationInfo.checkRequiredIdentifier(oid)) {
            int version = ((ASN1Integer) requiredData).getValue().intValue();
            if (optionalData == null) {
                return new ActiveAuthenticationInfo(oid, version, null);
            } else {
                String signatureAlgorithmOID = ((ASN1ObjectIdentifier) optionalData).getId();
                return new ActiveAuthenticationInfo(oid, version, signatureAlgorithmOID);
            }
        } else if (ChipAuthenticationPublicKeyInfo.checkRequiredIdentifier(oid)) {
            SubjectPublicKeyInfo subjectPublicKeyInfo = new SubjectPublicKeyInfo((ASN1Sequence) requiredData);
            if (optionalData == null) {
                return new ChipAuthenticationPublicKeyInfo(oid, subjectPublicKeyInfo);
            } else {
                ASN1Integer optionalDataAsASN1Integer = (ASN1Integer) optionalData;
                BigInteger keyId = optionalDataAsASN1Integer.getValue();
                return new ChipAuthenticationPublicKeyInfo(oid, subjectPublicKeyInfo, keyId);
            }
        } else if (ChipAuthenticationInfo.checkRequiredIdentifier(oid)) {
            int version = ((ASN1Integer) requiredData).getValue().intValue();
            if (optionalData == null) {
                return new ChipAuthenticationInfo(oid, version);
            } else {
                ASN1Integer optionalDataAsASN1Integer = (ASN1Integer) optionalData;
                BigInteger keyId = optionalDataAsASN1Integer.getValue();
                return new ChipAuthenticationInfo(oid, version, keyId);
            }
        } else if (TerminalAuthenticationInfo.checkRequiredIdentifier(oid)) {
            int version = ((ASN1Integer) requiredData).getValue().intValue();
            if (optionalData == null) {
                return new TerminalAuthenticationInfo(oid, version);
            } else {
                ASN1Sequence efCVCA = (ASN1Sequence) optionalData;
                return new TerminalAuthenticationInfo(oid, version, efCVCA);
            }
        } else if (PACEInfo.checkRequiredIdentifier(oid)) {
            int version = ((ASN1Integer) requiredData).getValue().intValue();
            int parameterId = -1;
            if (optionalData != null) {
                parameterId = ((ASN1Integer) optionalData).getValue().intValue();
            }
            return new PACEInfo(oid, version, parameterId);
        } else if (PACEDomainParameterInfo.checkRequiredIdentifier(oid)) {
            AlgorithmIdentifier domainParameters = AlgorithmIdentifier.getInstance(requiredData);
            if (optionalData != null) {
                int parameterId = ((ASN1Integer) optionalData).getValue().intValue();
                return new PACEDomainParameterInfo(oid, domainParameters, parameterId);
            }
            return new PACEDomainParameterInfo(oid, domainParameters);
        }
        //         throw new IllegalArgumentException("Malformed input stream.");
        LOGGER.warning("Unsupported SecurityInfo, oid = " + oid);
        return null;
    } catch (Exception e) {
        LOGGER.severe("Exception: " + e.getMessage());
        throw new IllegalArgumentException("Malformed input stream.");
    }
}

From source file:org.jmrtd.Util.java

License:Open Source License

/**
 * For ECDSA the EAC 1.11 specification requires the signature to be stripped down from any ASN.1 wrappers, as so.
 *
 * @param signedData signed data/*from  w  w w  .  ja va  2 s . com*/
 * @param keySize key size
 *
 * @return signature without wrappers
 *
 * @throws IOException on error
 */
public static byte[] getRawECDSASignature(byte[] signedData, int keySize) throws IOException {
    ASN1InputStream asn1In = new ASN1InputStream(signedData);
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        ASN1Sequence obj = (ASN1Sequence) asn1In.readObject();
        Enumeration<ASN1Primitive> e = obj.getObjects();
        while (e.hasMoreElements()) {
            ASN1Integer i = (ASN1Integer) e.nextElement();
            byte[] t = i.getValue().toByteArray();
            t = alignKeyDataToSize(t, keySize);
            out.write(t);
        }
        out.flush();
        return out.toByteArray();
    } finally {
        asn1In.close();
        out.close();
    }
}

From source file:org.jruby.ext.openssl.impl.Envelope.java

License:LGPL

/**
 * EnvelopedData ::= SEQUENCE {//from w  w w  .  jav  a2 s. co m
 *   version Version,
 *   recipientInfos RecipientInfos,
 *   encryptedContentInfo EncryptedContentInfo }
 *
 * Version ::= INTEGER
 *
 * RecipientInfos ::= SET OF RecipientInfo
 *
 */
public static Envelope fromASN1(ASN1Encodable content) {
    ASN1Sequence sequence = (ASN1Sequence) content;
    ASN1Integer version = (ASN1Integer) sequence.getObjectAt(0);
    ASN1Set recipients = (ASN1Set) sequence.getObjectAt(1);
    ASN1Encodable encContent = sequence.getObjectAt(2);

    Envelope envelope = new Envelope();
    envelope.setVersion(version.getValue().intValue());
    envelope.setRecipientInfo(recipientInfosFromASN1Set(recipients));
    envelope.setEncData(EncContent.fromASN1(encContent));

    return envelope;
}

From source file:org.jruby.ext.openssl.impl.PKey.java

License:LGPL

public static KeyPair readPrivateKey(byte[] input, String type) throws IOException, GeneralSecurityException {
    KeySpec pubSpec = null;//from  ww w .j av a  2  s .  c om
    KeySpec privSpec = null;
    ASN1Sequence seq = (ASN1Sequence) new ASN1InputStream(input).readObject();
    if (type.equals("RSA")) {
        ASN1Integer mod = (ASN1Integer) seq.getObjectAt(1);
        ASN1Integer pubExp = (ASN1Integer) seq.getObjectAt(2);
        ASN1Integer privExp = (ASN1Integer) seq.getObjectAt(3);
        ASN1Integer p1 = (ASN1Integer) seq.getObjectAt(4);
        ASN1Integer p2 = (ASN1Integer) seq.getObjectAt(5);
        ASN1Integer exp1 = (ASN1Integer) seq.getObjectAt(6);
        ASN1Integer exp2 = (ASN1Integer) seq.getObjectAt(7);
        ASN1Integer crtCoef = (ASN1Integer) seq.getObjectAt(8);
        pubSpec = new RSAPublicKeySpec(mod.getValue(), pubExp.getValue());
        privSpec = new RSAPrivateCrtKeySpec(mod.getValue(), pubExp.getValue(), privExp.getValue(),
                p1.getValue(), p2.getValue(), exp1.getValue(), exp2.getValue(), crtCoef.getValue());
    } else { // assume "DSA" for now.
        ASN1Integer p = (ASN1Integer) seq.getObjectAt(1);
        ASN1Integer q = (ASN1Integer) seq.getObjectAt(2);
        ASN1Integer g = (ASN1Integer) seq.getObjectAt(3);
        ASN1Integer y = (ASN1Integer) seq.getObjectAt(4);
        ASN1Integer x = (ASN1Integer) seq.getObjectAt(5);
        privSpec = new DSAPrivateKeySpec(x.getValue(), p.getValue(), q.getValue(), g.getValue());
        pubSpec = new DSAPublicKeySpec(y.getValue(), p.getValue(), q.getValue(), g.getValue());
    }
    KeyFactory fact = KeyFactory.getInstance(type);
    return new KeyPair(fact.generatePublic(pubSpec), fact.generatePrivate(privSpec));
}

From source file:org.jruby.ext.openssl.impl.Signed.java

License:LGPL

/**
 * SignedData ::= SEQUENCE {/*from w ww .ja  v  a  2  s.c o  m*/
 *   version Version,
 *   digestAlgorithms DigestAlgorithmIdentifiers,
 *   contentInfo ContentInfo,
 *   certificates [0] IMPLICIT ExtendedCertificatesAndCertificates OPTIONAL,
 *   crls [1] IMPLICIT CertificateRevocationLists OPTIONAL,
 *   signerInfos SignerInfos }
 *
 * Version ::= INTEGER
 *
 * DigestAlgorithmIdentifiers ::= SET OF DigestAlgorithmIdentifier
 *
 * SignerInfos ::= SET OF SignerInfo
 */
public static Signed fromASN1(ASN1Encodable content) throws PKCS7Exception {
    ASN1Sequence sequence = (ASN1Sequence) content;
    ASN1Integer version = (ASN1Integer) sequence.getObjectAt(0);
    ASN1Set digestAlgos = (ASN1Set) sequence.getObjectAt(1);
    ASN1Encodable contentInfo = sequence.getObjectAt(2);

    ASN1Encodable certificates = null;
    ASN1Encodable crls = null;

    int index = 3;
    ASN1Encodable tmp = sequence.getObjectAt(index);
    if ((tmp instanceof ASN1TaggedObject) && ((ASN1TaggedObject) tmp).getTagNo() == 0) {
        certificates = ((ASN1TaggedObject) tmp).getObject();
        index++;
    }

    tmp = sequence.getObjectAt(index);
    if ((tmp instanceof ASN1TaggedObject) && ((ASN1TaggedObject) tmp).getTagNo() == 1) {
        crls = ((ASN1TaggedObject) tmp).getObject();
        index++;
    }

    ASN1Set signerInfos = (ASN1Set) sequence.getObjectAt(index);

    Signed signed = new Signed();
    signed.setVersion(version.getValue().intValue());
    signed.setMdAlgs(algorithmIdentifiersFromASN1Set(digestAlgos));
    signed.setContents(PKCS7.fromASN1(contentInfo));
    if (certificates != null) {
        signed.setCert(certificatesFromASN1Set(certificates));
    }
    if (crls != null) {
        throw new RuntimeException("TODO: implement CRL part");
    }
    signed.setSignerInfo(signerInfosFromASN1Set(signerInfos));

    return signed;
}

From source file:org.kse.crypto.filetype.CryptoFileUtil.java

License:Open Source License

/**
 * Detect the KeyStore type contained in the supplied file.
 *
 * @param is/*from w w  w  .j  av  a2s . c  o m*/
 *            Input stream to detect type for
 * @return KeyStore type or null if none matched
 * @throws IOException
 *             If an I/O problem occurred
 */
public static KeyStoreType detectKeyStoreType(InputStream is) throws IOException {
    byte[] contents = ReadUtil.readFully(is);

    DataInputStream dis = null;

    try {
        dis = new DataInputStream(new ByteArrayInputStream(contents));

        // If less than 4 bytes are available it isn't a KeyStore
        if (dis.available() < 4) {
            return null;
        }

        // Read first integer (4 bytes)
        int i1 = dis.readInt();

        // Test for JKS - starts with appropriate magic number
        if (i1 == JKS_MAGIC_NUMBER) {
            return JKS;
        }

        // Test for JCEKS - starts with appropriate magic number
        if (i1 == JCEKS_MAGIC_NUMBER) {
            return JCEKS;
        }

        // Test for BKS and UBER

        // Both start with a version number of 0, 1 or 2
        if ((i1 == 0) || (i1 == 1) || (i1 == 2)) {
            /*
             * For BKS and UBER the last 20 bytes of the file are the SHA-1
             * Hash while the byte before that is a ASN1Null (0) indicating
             * the end of the store. UBER, however, encrypts the store
             * content making it highly unlikely that the ASN1Null end byte
             * will be preserved. Therefore if the 21st byte from the end of
             * the file is a ASN1Null then the KeyStore is BKS
             */

            if (contents.length < 26) {
                // Insufficient bytes to be BKS or UBER
                return null;
            }

            // Skip to 21st from last byte (file length minus 21 and the 4 bytes already read)
            dis.skip(contents.length - 25);

            // Read what may be the null byte
            if (dis.readByte() == 0) {
                // Found null byte - BKS/BKS-V1
                if (i1 == 1) {
                    return BKS_V1;
                } else {
                    return BKS;
                }
            } else {
                // No null byte - UBER
                return UBER;
            }
        }
    } finally {
        IOUtils.closeQuietly(dis);
    }

    // @formatter:off
    /*
     * Test for PKCS #12. ASN.1 should look like this:
     *
     * PFX ::= ASN1Sequence { version ASN1Integer {v3(3)}(v3,...), authSafe
     * ContentInfo, macData MacData OPTIONAL
     */
    // @formatter:on

    ASN1Primitive pfx = null;
    try {
        pfx = ASN1Primitive.fromByteArray(contents);
    } catch (IOException e) {
        // if it cannot be parsed as ASN1, it is certainly not a pfx key store
        return null;
    }

    // Is a sequence...
    if ((pfx != null) && (pfx instanceof ASN1Sequence)) {
        // Has two or three components...
        ASN1Sequence sequence = (ASN1Sequence) pfx;

        if ((sequence.size() == 2) || (sequence.size() == 3)) {
            // ...the first of which is a version of 3
            ASN1Encodable firstComponent = sequence.getObjectAt(0);

            if (firstComponent instanceof ASN1Integer) {
                ASN1Integer version = (ASN1Integer) firstComponent;

                if (version.getValue().intValue() == 3) {
                    return PKCS12;
                }
            }
        }
    }

    // KeyStore type not recognised
    return null;
}