Example usage for org.bouncycastle.asn1 ASN1Integer getInstance

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

Introduction

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

Prototype

public static ASN1Integer getInstance(Object obj) 

Source Link

Document

Return an integer from the passed in object.

Usage

From source file:org.cryptoworkshop.ximix.node.crypto.key.message.BLSCommittedSecretShareMessage.java

License:Apache License

private BLSCommittedSecretShareMessage(BLS01Parameters blsParameters, ASN1Sequence seq) {
    this.index = ASN1Integer.getInstance(seq.getObjectAt(0)).getValue().intValue();
    this.value = ASN1Integer.getInstance(seq.getObjectAt(1)).getValue();
    this.witness = ASN1Integer.getInstance(seq.getObjectAt(2)).getValue();

    ASN1Sequence s = ASN1Sequence.getInstance(seq.getObjectAt(3));

    this.commitmentFactors = new Element[s.size()];

    for (int i = 0; i != commitmentFactors.length; i++) {
        commitmentFactors[i] = blsParameters.getG().duplicate();
        commitmentFactors[i].setFromBytes(DEROctetString.getInstance(s.getObjectAt(i)).getOctets());
    }/* w  w w.  j  av a  2  s  . com*/

    Pairing pairing = PairingFactory.getPairing(blsParameters.getCurveParameters());
    this.pK = pairing.getG2().newElement();
    this.pK.setFromBytes(DEROctetString.getInstance(seq.getObjectAt(4)).getOctets());
}

From source file:org.cryptoworkshop.ximix.node.crypto.key.message.ECCommittedSecretShareMessage.java

License:Apache License

private ECCommittedSecretShareMessage(ECCurve curve, ASN1Sequence seq) {
    this.index = ASN1Integer.getInstance(seq.getObjectAt(0)).getValue().intValue();
    this.value = ASN1Integer.getInstance(seq.getObjectAt(1)).getValue();
    this.witness = ASN1Integer.getInstance(seq.getObjectAt(2)).getValue();

    ASN1Sequence pSeq = ASN1Sequence.getInstance(seq.getObjectAt(3));

    this.commitmentFactors = new ECPoint[pSeq.size()];

    for (int i = 0; i != commitmentFactors.length; i++) {
        byte[] enc = ASN1OctetString.getInstance(pSeq.getObjectAt(i)).getOctets();

        commitmentFactors[i] = curve.decodePoint(enc);
    }//  w  w  w. j av a 2  s.c o  m

    this.q = curve.decodePoint(ASN1OctetString.getInstance(seq.getObjectAt(4)).getOctets());

    ASN1Sequence qSeq = ASN1Sequence.getInstance(seq.getObjectAt(5));

    this.qCommitmentFactors = new ECPoint[qSeq.size()];

    for (int i = 0; i != commitmentFactors.length; i++) {
        byte[] enc = ASN1OctetString.getInstance(qSeq.getObjectAt(i)).getOctets();

        qCommitmentFactors[i] = curve.decodePoint(enc);
    }
}

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

License:Open Source License

@Override
public boolean create() throws InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException {
    boolean ret = false;
    // Some general stuff, common for all types of messages
    String issuer = null;//  w  w  w .  ja  v a2s  .  co m
    String subject = null;
    if (cert != null) {
        X509Certificate x509cert = (X509Certificate) cert;
        issuer = x509cert.getIssuerDN().getName();
        subject = x509cert.getSubjectDN().getName();
    } else if ((signCertChain != null) && (signCertChain.size() > 0)) {
        issuer = ((X509Certificate) signCertChain.iterator().next()).getSubjectDN().getName();
        subject = "CN=fooSubject";
    } else {
        issuer = "CN=fooIssuer";
        subject = "CN=fooSubject";
    }

    final GeneralName issuerName = new GeneralName(new X500Name(issuer));
    final GeneralName subjectName = new GeneralName(new X500Name(subject));
    final PKIHeaderBuilder myPKIHeader = CmpMessageHelper.createPKIHeaderBuilder(issuerName, subjectName,
            senderNonce, recipientNonce, transactionId);
    PKIBody myPKIBody = null;
    final PKIMessage myPKIMessage;

    try {
        if (status.equals(ResponseStatus.SUCCESS)) {
            if (cert != null) {
                if (log.isDebugEnabled()) {
                    log.debug("Creating a CertRepMessage 'accepted'");
                }
                PKIStatusInfo myPKIStatusInfo = new PKIStatusInfo(PKIStatus.granted); // 0 = accepted
                ASN1InputStream certASN1InputStream = new ASN1InputStream(
                        new ByteArrayInputStream(cert.getEncoded()));
                ASN1InputStream cacertASN1InputStream = new ASN1InputStream(
                        new ByteArrayInputStream(cacert.getEncoded()));
                try {
                    try {
                        CMPCertificate cmpcert = CMPCertificate.getInstance(certASN1InputStream.readObject());
                        CertOrEncCert retCert = new CertOrEncCert(cmpcert);
                        CertifiedKeyPair myCertifiedKeyPair = new CertifiedKeyPair(retCert);
                        CertResponse myCertResponse = new CertResponse(new ASN1Integer(requestId),
                                myPKIStatusInfo, myCertifiedKeyPair, null);

                        CertResponse[] certRespos = { myCertResponse };
                        CMPCertificate[] caPubs = {
                                CMPCertificate.getInstance(cacertASN1InputStream.readObject()) };

                        CertRepMessage myCertRepMessage = new CertRepMessage(caPubs, certRespos);

                        int respType = requestType + 1; // 1 = intitialization response, 3 = certification response etc
                        if (log.isDebugEnabled()) {
                            log.debug("Creating response body of type " + respType);
                        }
                        myPKIBody = new PKIBody(respType, myCertRepMessage);
                    } finally {
                        certASN1InputStream.close();
                        cacertASN1InputStream.close();
                    }
                } catch (IOException e) {
                    throw new IllegalStateException("Unexpected IOException caught.", e);
                }
            }
        } else if (status.equals(ResponseStatus.FAILURE)) {
            if (log.isDebugEnabled()) {
                log.debug("Creating a CertRepMessage 'rejected'");
            }
            // Create a failure message
            ASN1EncodableVector statusInfoV = new ASN1EncodableVector();
            statusInfoV.add(ASN1Integer.getInstance(PKIStatus.rejection.toASN1Primitive()));
            if (failText != null) {
                statusInfoV.add(new PKIFreeText(new DERUTF8String(failText)));
            }
            statusInfoV.add(CmpMessageHelper.getPKIFailureInfo(failInfo.intValue()));
            PKIStatusInfo myPKIStatusInfo = PKIStatusInfo
                    .getInstance(ASN1Sequence.getInstance(new DERSequence(statusInfoV)));
            myPKIBody = CmpMessageHelper.createCertRequestRejectBody(myPKIStatusInfo, requestId, requestType);

        } else {
            if (log.isDebugEnabled()) {
                log.debug("Creating a 'waiting' message?");
            }
            // Not supported, lets create a PKIError failure instead
            // Create a failure message
            ASN1EncodableVector statusInfoV = new ASN1EncodableVector();
            statusInfoV.add(PKIStatus.rejection); // 2 = rejection
            if (failText != null) {
                statusInfoV.add(new PKIFreeText(new DERUTF8String(failText)));
            }
            statusInfoV.add(CmpMessageHelper.getPKIFailureInfo(failInfo.intValue()));
            PKIStatusInfo myPKIStatusInfo = PKIStatusInfo.getInstance(new DERSequence(statusInfoV));

            ErrorMsgContent myErrorContent = new ErrorMsgContent(myPKIStatusInfo);
            myPKIBody = new PKIBody(23, myErrorContent); // 23 = error                
        }

        if ((pbeKeyId != null) && (pbeKey != null) && (pbeDigestAlg != null) && (pbeMacAlg != null)) {
            myPKIHeader.setProtectionAlg(new AlgorithmIdentifier(CMPObjectIdentifiers.passwordBasedMac));
            PKIHeader header = myPKIHeader.build();
            myPKIMessage = new PKIMessage(header, myPKIBody);
            responseMessage = CmpMessageHelper.protectPKIMessageWithPBE(myPKIMessage, pbeKeyId, pbeKey,
                    pbeDigestAlg, pbeMacAlg, pbeIterationCount);
        } else {
            myPKIHeader.setProtectionAlg(new AlgorithmIdentifier(digest));
            PKIHeader header = myPKIHeader.build();
            myPKIMessage = new PKIMessage(header, myPKIBody);
            responseMessage = CmpMessageHelper.signPKIMessage(myPKIMessage, signCertChain, signKey, digest,
                    provider);
        }

        ret = true;

    } catch (CertificateEncodingException e) {
        log.error("Error creating CertRepMessage: ", e);
    } catch (InvalidKeyException e) {
        log.error("Error creating CertRepMessage: ", e);
    } catch (NoSuchProviderException e) {
        log.error("Error creating CertRepMessage: ", e);
    } catch (NoSuchAlgorithmException e) {
        log.error("Error creating CertRepMessage: ", e);
    } catch (SecurityException e) {
        log.error("Error creating CertRepMessage: ", e);
    } catch (SignatureException e) {
        log.error("Error creating CertRepMessage: ", e);
    }

    return ret;
}

From source file:org.jruby.ext.openssl.impl.pem.MiscPEMGenerator.java

License:Open Source License

private PemObject createPemObject(Object o) throws IOException {
    String type;//from w ww.jav a 2 s .  c om
    byte[] encoding;

    if (o instanceof PemObject) {
        return (PemObject) o;
    }
    if (o instanceof PemObjectGenerator) {
        return ((PemObjectGenerator) o).generate();
    }
    if (o instanceof X509CertificateHolder) {
        type = "CERTIFICATE";
        encoding = ((X509CertificateHolder) o).getEncoded();
    } else if (o instanceof X509CRLHolder) {
        type = "X509 CRL";
        encoding = ((X509CRLHolder) o).getEncoded();
    } else if (o instanceof PrivateKeyInfo) {
        PrivateKeyInfo info = (PrivateKeyInfo) o;
        ASN1ObjectIdentifier algOID = info.getPrivateKeyAlgorithm().getAlgorithm();

        if (algOID.equals(PKCSObjectIdentifiers.rsaEncryption)) {
            type = "RSA PRIVATE KEY";
            encoding = info.parsePrivateKey().toASN1Primitive().getEncoded();
        } else if (algOID.equals(dsaOids[0]) || algOID.equals(dsaOids[1])) {
            type = "DSA PRIVATE KEY";

            DSAParameter p = DSAParameter.getInstance(info.getPrivateKeyAlgorithm().getParameters());
            ASN1EncodableVector v = new ASN1EncodableVector();

            v.add(new ASN1Integer(BigInteger.ZERO));
            v.add(new ASN1Integer(p.getP()));
            v.add(new ASN1Integer(p.getQ()));
            v.add(new ASN1Integer(p.getG()));

            BigInteger x = ASN1Integer.getInstance(info.parsePrivateKey()).getValue();
            BigInteger y = p.getG().modPow(x, p.getP());

            v.add(new ASN1Integer(y));
            v.add(new ASN1Integer(x));

            encoding = new DERSequence(v).getEncoded();
        } else if (algOID.equals(X9ObjectIdentifiers.id_ecPublicKey)) {
            type = "EC PRIVATE KEY";
            encoding = info.parsePrivateKey().toASN1Primitive().getEncoded();
        } else {
            throw new IOException("Cannot identify private key");
        }
    } else if (o instanceof SubjectPublicKeyInfo) {
        type = "PUBLIC KEY";
        encoding = ((SubjectPublicKeyInfo) o).getEncoded();
    } else if (o instanceof X509AttributeCertificateHolder) {
        type = "ATTRIBUTE CERTIFICATE";
        encoding = ((X509AttributeCertificateHolder) o).getEncoded();
    } else if (o instanceof PKCS10CertificationRequest) {
        type = "CERTIFICATE REQUEST";
        encoding = ((PKCS10CertificationRequest) o).getEncoded();
    } else if (o instanceof ContentInfo) {
        type = "PKCS7";
        encoding = ((ContentInfo) o).getEncoded();
    }
    //
    // NOTE: added behaviour to provide backwards compatibility with 1.47 :
    //
    else if (o instanceof java.security.cert.X509Certificate) // 1.47 compatibility
    {
        type = "CERTIFICATE";
        try {
            encoding = ((java.security.cert.X509Certificate) o).getEncoded();
        } catch (CertificateEncodingException e) {
            throw new PemGenerationException("Cannot encode object: " + e.toString());
        }
    } else if (o instanceof java.security.cert.X509CRL) // 1.47 compatibility
    {
        type = "X509 CRL";
        try {
            encoding = ((java.security.cert.X509CRL) o).getEncoded();
        } catch (CRLException e) {
            throw new PemGenerationException("Cannot encode object: " + e.toString());
        }
    } else if (o instanceof java.security.KeyPair) // 1.47 compatibility
    {
        return createPemObject(((java.security.KeyPair) o).getPrivate());
    } else if (o instanceof java.security.PrivateKey) // 1.47 compatibility
    {
        PrivateKeyInfo info = new PrivateKeyInfo(
                (ASN1Sequence) ASN1Primitive.fromByteArray(((java.security.Key) o).getEncoded()));

        if (o instanceof java.security.interfaces.RSAPrivateKey) {
            type = "RSA PRIVATE KEY";

            encoding = info.parsePrivateKey().toASN1Primitive().getEncoded();
        } else if (o instanceof java.security.interfaces.DSAPrivateKey) {
            type = "DSA PRIVATE KEY";

            DSAParameter p = DSAParameter.getInstance(info.getPrivateKeyAlgorithm().getParameters());
            ASN1EncodableVector v = new ASN1EncodableVector();

            v.add(new DERInteger(0));
            v.add(new DERInteger(p.getP()));
            v.add(new DERInteger(p.getQ()));
            v.add(new DERInteger(p.getG()));

            BigInteger x = ((java.security.interfaces.DSAPrivateKey) o).getX();
            BigInteger y = p.getG().modPow(x, p.getP());

            v.add(new DERInteger(y));
            v.add(new DERInteger(x));

            encoding = new DERSequence(v).getEncoded();
        } else if (((java.security.PrivateKey) o).getAlgorithm().equals("ECDSA")) {
            type = "EC PRIVATE KEY";

            encoding = info.parsePrivateKey().toASN1Primitive().getEncoded();
        } else {
            throw new IOException("Cannot identify private key");
        }
    } else if (o instanceof java.security.PublicKey) // 1.47 compatibility
    {
        type = "PUBLIC KEY";

        encoding = ((java.security.PublicKey) o).getEncoded();
    } else if (o instanceof X509AttributeCertificate) // 1.47 compatibility
    {
        type = "ATTRIBUTE CERTIFICATE";
        encoding = ((X509AttributeCertificate) o).getEncoded();
    }
    //
    //
    //
    else {
        throw new PemGenerationException("unknown object passed - can't encode.");
    }

    if (encryptor != null) // NEW STUFF (NOT IN OLD)
    {
        String dekAlgName = Strings.toUpperCase(encryptor.getAlgorithm());

        // Note: For backward compatibility
        if (dekAlgName.equals("DESEDE")) {
            dekAlgName = "DES-EDE3-CBC";
        }

        byte[] iv = encryptor.getIV();
        byte[] encData = encryptor.encrypt(encoding);

        List<PemHeader> headers = new ArrayList<PemHeader>(2);

        headers.add(new PemHeader("Proc-Type", "4,ENCRYPTED"));
        headers.add(new PemHeader("DEK-Info", dekAlgName + "," + getHexEncoded(iv)));

        return new PemObject(type, headers, encData);
    }
    return new PemObject(type, encoding);
}

From source file:org.kse.crypto.x509.X509Ext.java

License:Open Source License

private String getQcStatementsStringValue(byte[] octets) throws IOException {

    // @formatter:off

    /*/*  w w  w.ja  va2 s .  c om*/
       QCStatements ::= SEQUENCE OF QSStatement
        QSStatement ::= SEQUENCE
        {
      statementId OBJECT IDENTIFIER,
      statementInfo ANY DEFINED BY statementId OPTIONAL
        }
        QcEuLimitValue ::= MonetaryValue
       QcRetentionPeriod ::= INTEGER
     */

    // @formatter:on

    StringBuilder sb = new StringBuilder();

    int qcStatementNr = 0;

    ASN1Sequence qcStatements = ASN1Sequence.getInstance(octets);
    for (ASN1Encodable asn1Encodable : qcStatements.toArray()) {
        QCStatement qcStatement = QCStatement.getInstance(asn1Encodable);
        ASN1ObjectIdentifier statementId = qcStatement.getStatementId();
        ASN1Encodable statementInfo = qcStatement.getStatementInfo();

        int indentLevel = 1;

        sb.append(MessageFormat.format(res.getString("QCStatement.QCStatement"), ++qcStatementNr));
        sb.append(NEWLINE);

        QcStatementType qcStatementType = QcStatementType.resolveOid(statementId.getId());
        if (qcStatementType != null) {
            switch (qcStatementType) {
            case QC_SYNTAX_V1:
            case QC_SYNTAX_V2:
                SemanticsInformation semanticsInfo = SemanticsInformation.getInstance(statementInfo);
                sb.append(getSemanticInformationValueString(qcStatementType, semanticsInfo, indentLevel));
                break;
            case QC_COMPLIANCE:
                // no statementInfo
                sb.append(INDENT.toString(indentLevel));
                sb.append(res.getString(QcStatementType.QC_COMPLIANCE.getResKey()));
                sb.append(NEWLINE);
                break;
            case QC_EU_LIMIT_VALUE:
                sb.append(INDENT.toString(indentLevel));
                sb.append(res.getString(QcStatementType.QC_EU_LIMIT_VALUE.getResKey()));
                sb.append(NEWLINE);
                sb.append(getMonetaryValueStringValue(statementInfo, indentLevel + 1));
                break;
            case QC_RETENTION_PERIOD:
                ASN1Integer asn1Integer = ASN1Integer.getInstance(statementInfo);
                sb.append(INDENT.toString(indentLevel));
                sb.append(MessageFormat.format(res.getString(QcStatementType.QC_RETENTION_PERIOD.getResKey()),
                        asn1Integer.getValue().toString()));
                sb.append(NEWLINE);
                break;
            case QC_SSCD:
                // no statementInfo
                sb.append(INDENT.toString(indentLevel));
                sb.append(res.getString(QcStatementType.QC_SSCD.getResKey()));
                sb.append(NEWLINE);
                break;
            case QC_PDS:
                ASN1Sequence pdsLocations = ASN1Sequence.getInstance(statementInfo);
                sb.append(INDENT.toString(indentLevel));
                sb.append(res.getString(QcStatementType.QC_PDS.getResKey()));
                for (ASN1Encodable pdsLoc : pdsLocations) {
                    sb.append(NEWLINE);
                    sb.append(INDENT.toString(indentLevel + 1));
                    DLSequence pds = (DLSequence) pdsLoc;
                    sb.append(MessageFormat.format(res.getString("QCPDS.locations"), pds.getObjectAt(1),
                            pds.getObjectAt(0)));
                }
                sb.append(NEWLINE);
                break;
            case QC_TYPE:
                sb.append(INDENT.toString(indentLevel));
                sb.append(res.getString(QcStatementType.QC_TYPE.getResKey()));
                ASN1Sequence qcTypes = ASN1Sequence.getInstance(statementInfo);
                for (ASN1Encodable type : qcTypes) {
                    sb.append(NEWLINE);
                    sb.append(INDENT.toString(indentLevel + 1));
                    sb.append(ObjectIdUtil.toString((ASN1ObjectIdentifier) type));
                }
                sb.append(NEWLINE);
            }
        } else {
            // no statementInfo
            sb.append(INDENT.toString(indentLevel));
            sb.append(statementId.getId());
            sb.append(statementInfo.toString());
            sb.append(NEWLINE);
        }
    }

    return sb.toString();

}

From source file:org.signserver.module.tsa.MSAuthCodeTimeStampSigner.java

License:Open Source License

/**
 * The main method performing the actual timestamp operation.
 * Expects the signRequest to be a GenericSignRequest contining a
 * TimeStampRequest//  ww w  .  j a  va2s.com
 *
 * @param signRequest
 * @param requestContext
 * @return the sign response
 * @see org.signserver.server.IProcessable#processData(org.signserver.common.ProcessRequest, org.signserver.common.RequestContext)
 */
public ProcessResponse processData(final ProcessRequest signRequest, final RequestContext requestContext)
        throws IllegalRequestException, CryptoTokenOfflineException, SignServerException {

    // Log values
    final LogMap logMap = LogMap.getInstance(requestContext);

    try {
        final ISignRequest sReq = (ISignRequest) signRequest;
        final byte[] requestbytes = (byte[]) sReq.getRequestData();

        if (requestbytes == null || requestbytes.length == 0) {
            LOG.error("Request must contain data");
            throw new IllegalRequestException("Request must contain data");
        }

        // Check that the request contains a valid TimeStampRequest object.
        if (!(signRequest instanceof GenericSignRequest)) {
            final IllegalRequestException exception = new IllegalRequestException(
                    "Recieved request wasn't an expected GenericSignRequest. ");
            LOG.error("Received request wasn't an expected GenericSignRequest");
            throw exception;
        }

        if (!((sReq.getRequestData() instanceof TimeStampRequest)
                || (sReq.getRequestData() instanceof byte[]))) {
            final IllegalRequestException exception = new IllegalRequestException(
                    "Recieved request data wasn't an expected TimeStampRequest. ");
            LOG.error("Received request data wasn't an expected TimeStampRequest");
            throw exception;
        }

        if (!validChain) {
            LOG.error("Certificate chain not correctly configured");
            throw new CryptoTokenOfflineException("Certificate chain not correctly configured");
        }

        ASN1Primitive asn1obj = ASN1Primitive.fromByteArray(Base64.decode(requestbytes));
        ASN1Sequence asn1seq = ASN1Sequence.getInstance(asn1obj);

        if (asn1seq.size() != 2) {
            LOG.error("Wrong structure, should be an ASN1Sequence with 2 elements");
            throw new IllegalRequestException("Wrong structure, should be an ASN1Sequence with 2 elements");
        }

        ASN1ObjectIdentifier oid = ASN1ObjectIdentifier.getInstance(asn1seq.getObjectAt(0));
        ASN1Sequence asn1seq1 = ASN1Sequence.getInstance(asn1seq.getObjectAt(1));

        final ContentInfo ci = new ContentInfo(asn1seq1);

        if (!oid.getId().equals(msOID)) {
            LOG.error("Invalid OID in request: " + oid.getId());
            throw new IllegalRequestException("Invalid OID in request: " + oid.getId());
        }

        if (asn1seq1.size() != 2) {
            LOG.error(
                    "Wrong structure, should be an ASN1Sequence with 2 elements as the value of element 0 in the outer ASN1Sequence");
            throw new IllegalRequestException(
                    "Wrong structure, should be an ASN1Sequence with 2 elements as the value of element 0 in the outer ASN1Sequence");
        }

        oid = ASN1ObjectIdentifier.getInstance(asn1seq1.getObjectAt(0));

        if (!oid.getId().equals(dataOID)) {
            throw new IllegalRequestException("Wrong contentType OID: " + oid.getId());
        }

        ASN1TaggedObject tag = ASN1TaggedObject.getInstance(asn1seq1.getObjectAt(1));

        if (tag.getTagNo() != 0) {
            throw new IllegalRequestException("Wrong tag no (should be 0): " + tag.getTagNo());
        }

        ASN1OctetString octets = ASN1OctetString.getInstance(tag.getObject());
        byte[] content = octets.getOctets();

        final ITimeSource timeSrc;
        final Date date;
        byte[] der;
        ICryptoInstance crypto = null;
        try {
            crypto = acquireCryptoInstance(ICryptoToken.PURPOSE_SIGN, signRequest, requestContext);

            // get signing cert certificate chain and private key
            List<Certificate> certList = this.getSigningCertificateChain(crypto);
            if (certList == null) {
                throw new SignServerException("Null certificate chain. This signer needs a certificate.");
            }

            Certificate[] certs = (Certificate[]) certList.toArray(new Certificate[certList.size()]);

            // Sign
            X509Certificate x509cert = (X509Certificate) certs[0];

            timeSrc = getTimeSource();
            if (LOG.isDebugEnabled()) {
                LOG.debug("TimeSource: " + timeSrc.getClass().getName());
            }
            date = timeSrc.getGenTime();

            if (date == null) {
                throw new ServiceUnavailableException("Time source is not available");
            }

            ASN1EncodableVector signedAttributes = new ASN1EncodableVector();
            signedAttributes.add(new Attribute(CMSAttributes.signingTime, new DERSet(new Time(date))));

            if (includeSigningCertificateAttribute) {
                try {
                    final DERInteger serial = new DERInteger(x509cert.getSerialNumber());
                    final X509CertificateHolder certHolder = new X509CertificateHolder(x509cert.getEncoded());
                    final X500Name issuer = certHolder.getIssuer();
                    final GeneralName name = new GeneralName(issuer);
                    final GeneralNames names = new GeneralNames(name);
                    final IssuerSerial is = new IssuerSerial(names, ASN1Integer.getInstance(serial));

                    final ESSCertID essCertid = new ESSCertID(
                            MessageDigest.getInstance("SHA-1").digest(x509cert.getEncoded()), is);
                    signedAttributes.add(new Attribute(PKCSObjectIdentifiers.id_aa_signingCertificate,
                            new DERSet(new SigningCertificate(essCertid))));
                } catch (NoSuchAlgorithmException e) {
                    LOG.error("Can't find SHA-1 implementation: " + e.getMessage());
                    throw new SignServerException("Can't find SHA-1 implementation", e);
                }
            }

            AttributeTable signedAttributesTable = new AttributeTable(signedAttributes);
            DefaultSignedAttributeTableGenerator signedAttributeGenerator = new DefaultSignedAttributeTableGenerator(
                    signedAttributesTable);

            final String provider = cryptoToken.getProvider(ICryptoToken.PROVIDERUSAGE_SIGN);

            SignerInfoGeneratorBuilder signerInfoBuilder = new SignerInfoGeneratorBuilder(
                    new JcaDigestCalculatorProviderBuilder().setProvider("BC").build());
            signerInfoBuilder.setSignedAttributeGenerator(signedAttributeGenerator);

            JcaContentSignerBuilder contentSigner = new JcaContentSignerBuilder(signatureAlgo);
            contentSigner.setProvider(provider);

            final SignerInfoGenerator sig = signerInfoBuilder.build(contentSigner.build(crypto.getPrivateKey()),
                    new X509CertificateHolder(x509cert.getEncoded()));

            JcaCertStore cs = new JcaCertStore(certList);

            CMSTypedData cmspba = new CMSProcessableByteArray(content);
            CMSSignedData cmssd = MSAuthCodeCMSUtils.generate(cmspba, true, Arrays.asList(sig),
                    MSAuthCodeCMSUtils.getCertificatesFromStore(cs), Collections.emptyList(), ci);

            der = ASN1Primitive.fromByteArray(cmssd.getEncoded()).getEncoded();
        } finally {
            releaseCryptoInstance(crypto, requestContext);
        }

        // Log values
        logMap.put(ITimeStampLogger.LOG_TSA_TIME, String.valueOf(date.getTime()));
        logMap.put(ITimeStampLogger.LOG_TSA_TIMESOURCE, timeSrc.getClass().getSimpleName());

        final String archiveId = createArchiveId(requestbytes,
                (String) requestContext.get(RequestContext.TRANSACTION_ID));

        final GenericSignResponse signResponse;
        byte[] signedbytes = Base64.encode(der, false);

        logMap.put(ITimeStampLogger.LOG_TSA_TIMESTAMPRESPONSE_ENCODED, new String(signedbytes));

        final Collection<? extends Archivable> archivables = Arrays.asList(
                new DefaultArchivable(Archivable.TYPE_REQUEST, REQUEST_CONTENT_TYPE, requestbytes, archiveId),
                new DefaultArchivable(Archivable.TYPE_RESPONSE, RESPONSE_CONTENT_TYPE, signedbytes, archiveId));

        if (signRequest instanceof GenericServletRequest) {
            signResponse = new GenericServletResponse(sReq.getRequestID(), signedbytes,
                    getSigningCertificate(signRequest, requestContext), archiveId, archivables,
                    RESPONSE_CONTENT_TYPE);
        } else {
            signResponse = new GenericSignResponse(sReq.getRequestID(), signedbytes,
                    getSigningCertificate(signRequest, requestContext), archiveId, archivables);
        }

        // The client can be charged for the request
        requestContext.setRequestFulfilledByWorker(true);

        return signResponse;

    } catch (IOException e) {
        final IllegalRequestException exception = new IllegalRequestException("IOException: " + e.getMessage(),
                e);
        LOG.error("IOException: ", e);
        logMap.put(ITimeStampLogger.LOG_TSA_EXCEPTION, exception.getMessage());
        throw exception;
    } catch (CMSException e) {
        final SignServerException exception = new SignServerException(e.getMessage(), e);
        LOG.error("CMSException: ", e);
        logMap.put(ITimeStampLogger.LOG_TSA_EXCEPTION, exception.getMessage());
        throw exception;
    } catch (OperatorCreationException e) {
        final SignServerException exception = new SignServerException(e.getMessage(), e);
        LOG.error("OperatorCreationException: ", e);
        logMap.put(ITimeStampLogger.LOG_TSA_EXCEPTION, exception.getMessage());
        throw exception;
    } catch (CertificateEncodingException e) {
        final SignServerException exception = new SignServerException(e.getMessage(), e);
        LOG.error("CertificateEncodingException: ", e);
        logMap.put(ITimeStampLogger.LOG_TSA_EXCEPTION, exception.getMessage());
        throw exception;
    } catch (ArrayIndexOutOfBoundsException e) {
        // the BC base64 decoder doesn't check the the base64 input length...
        final IllegalRequestException exception = new IllegalRequestException(
                "ArrayIndexOutOfBoundsException: " + e.getMessage(), e);
        LOG.error("ArrayIndexOutOfBoundsException: ", e);
        logMap.put(ITimeStampLogger.LOG_TSA_EXCEPTION, exception.getMessage());
        throw exception;
    }
}

From source file:org.signserver.testutils.TestUtils.java

License:Open Source License

public static void checkSigningCertificateAttribute(final ASN1Sequence scAttr, final X509Certificate cert)
        throws Exception {
    final ASN1ObjectIdentifier scOid = ASN1ObjectIdentifier.getInstance(scAttr.getObjectAt(0));

    assertEquals("Invalid OID for content", SIGNING_CERT_OID, scOid.getId());

    // calculate expected hash
    final byte[] digest = MessageDigest.getInstance("SHA-1").digest(cert.getEncoded());

    // find hash in returned structure
    final ASN1Set set = ASN1Set.getInstance(scAttr.getObjectAt(1));
    final ASN1Sequence s1 = ASN1Sequence.getInstance(set.getObjectAt(0));
    final ASN1Sequence s2 = ASN1Sequence.getInstance(s1.getObjectAt(0));
    final ASN1Sequence s3 = ASN1Sequence.getInstance(s2.getObjectAt(0));
    final ASN1OctetString hashOctetString = ASN1OctetString.getInstance(s3.getObjectAt(0));

    assertTrue("Hash doesn't match", Arrays.equals(digest, hashOctetString.getOctets()));

    // find serial number in structure
    final ASN1Sequence s4 = ASN1Sequence.getInstance(s3.getObjectAt(1));
    final ASN1Integer snValue = ASN1Integer.getInstance(s4.getObjectAt(1));

    final BigInteger sn = cert.getSerialNumber();
    assertEquals("Serial number doesn't match", sn, snValue.getValue());

    // examine issuer
    final ASN1Sequence s5 = ASN1Sequence.getInstance(s4.getObjectAt(0));
    final ASN1TaggedObject obj = ASN1TaggedObject.getInstance(s5.getObjectAt(0));
    final ASN1Sequence s6 = ASN1Sequence.getInstance(obj.getObject());

    // expect 4 DN components in the signing cert
    assertEquals("Number of DN components", 4, s6.size());

    final Enumeration objects = s6.getObjects();
    while (objects.hasMoreElements()) {
        final ASN1Set component = ASN1Set.getInstance(objects.nextElement());
        final ASN1Sequence seq = ASN1Sequence.getInstance(component.getObjectAt(0));
        final ASN1ObjectIdentifier dnOid = ASN1ObjectIdentifier.getInstance(seq.getObjectAt(0));

        if (CN_OID.equals(dnOid.getId())) {
            final DERUTF8String cn = DERUTF8String.getInstance(seq.getObjectAt(1));
            assertEquals("Issuer CN doesn't match", CN, cn.getString());
        } else if (OU_OID.equals(dnOid.getId())) {
            final DERUTF8String ou = DERUTF8String.getInstance(seq.getObjectAt(1));
            assertEquals("Issuer OU doesn't match", OU, ou.getString());
        } else if (O_OID.equals(dnOid.getId())) {
            final DERUTF8String o = DERUTF8String.getInstance(seq.getObjectAt(1));
            assertEquals("Issuer O doesn't match", O, o.getString());
        } else if (C_OID.equals(dnOid.getId())) {
            final DERPrintableString c = DERPrintableString.getInstance(seq.getObjectAt(1));
            assertEquals("Issuer C doesn't match", C, c.getString());
        } else {//from   w w w  . ja  v a 2s  . c  o  m
            fail("Unexpected issuer DN component");
        }
    }
}

From source file:org.usrz.libs.crypto.pem.PEMFactory.java

License:Apache License

public PrivateKey getPrivateKey(PrivateKeyInfo keyInfo)
        throws NoSuchAlgorithmException, InvalidKeyException, InvalidKeySpecException {

    final Object algorithmId = keyInfo.getPrivateKeyAlgorithm().getAlgorithm();
    final ASN1Encodable encodable;
    try {//from   w w  w  .j av  a2  s. co  m
        encodable = keyInfo.parsePrivateKey();
    } catch (IOException exception) {
        throw new InvalidKeyException("Unable to parse private key structure", exception);
    }

    /* DSA keys */
    if (algorithmId.equals(X9ObjectIdentifiers.id_dsa)) {
        final ASN1Encodable encodedParams = keyInfo.getPrivateKeyAlgorithm().getParameters();
        final DSAParameter params = DSAParameter.getInstance(encodedParams);
        final BigInteger x = ASN1Integer.getInstance(encodable).getValue();
        return getDSAKeyFactory()
                .generatePrivate(new DSAPrivateKeySpec(x, params.getP(), params.getQ(), params.getG()));
    }

    /* RSA keys */
    if (algorithmId.equals(PKCSObjectIdentifiers.rsaEncryption)) {
        final RSAPrivateKey privateKey = RSAPrivateKey.getInstance(encodable);
        return getRSAKeyFactory().generatePrivate(
                new RSAPrivateCrtKeySpec(privateKey.getModulus(), privateKey.getPublicExponent(),
                        privateKey.getPrivateExponent(), privateKey.getPrime1(), privateKey.getPrime2(),
                        privateKey.getExponent1(), privateKey.getExponent2(), privateKey.getCoefficient()));
    }

    /* Others? */
    throw new NoSuchAlgorithmException("Unsupported algorithm for private key: " + algorithmId);

}

From source file:org.xipki.ca.api.profile.x509.BaseX509Certprofile.java

License:Open Source License

@Override
public SubjectPublicKeyInfo checkPublicKey(final SubjectPublicKeyInfo publicKey)
        throws BadCertTemplateException {
    Map<ASN1ObjectIdentifier, KeyParametersOption> keyAlgorithms = getKeyAlgorithms();
    if (CollectionUtil.isEmpty(keyAlgorithms)) {
        return publicKey;
    }//from   w ww  . ja  v a 2 s . co m

    ASN1ObjectIdentifier keyType = publicKey.getAlgorithm().getAlgorithm();
    if (keyAlgorithms.containsKey(keyType) == false) {
        throw new BadCertTemplateException("key type " + keyType.getId() + " is not permitted");
    }

    KeyParametersOption keyParamsOption = keyAlgorithms.get(keyType);
    if (keyParamsOption instanceof AllowAllParametersOption) {
        return publicKey;
    } else if (keyParamsOption instanceof ECParamatersOption) {
        ECParamatersOption ecOption = (ECParamatersOption) keyParamsOption;
        // parameters
        ASN1Encodable algParam = publicKey.getAlgorithm().getParameters();
        ASN1ObjectIdentifier curveOid;

        if (algParam instanceof ASN1ObjectIdentifier) {
            curveOid = (ASN1ObjectIdentifier) algParam;
            if (ecOption.allowsCurve(curveOid) == false) {
                throw new BadCertTemplateException("EC curve " + SecurityUtil.getCurveName(curveOid) + " (OID: "
                        + curveOid.getId() + ") is not allowed");
            }
        } else {
            throw new BadCertTemplateException("only namedCurve or implictCA EC public key is supported");
        }

        // point encoding
        if (ecOption.getPointEncodings() != null) {
            byte[] keyData = publicKey.getPublicKeyData().getBytes();
            if (keyData.length < 1) {
                throw new BadCertTemplateException("invalid publicKeyData");
            }
            byte pointEncoding = keyData[0];
            if (ecOption.getPointEncodings().contains(pointEncoding) == false) {
                throw new BadCertTemplateException("unaccepted EC point encoding " + pointEncoding);
            }
        }

        byte[] keyData = publicKey.getPublicKeyData().getBytes();
        try {
            checkECSubjectPublicKeyInfo(curveOid, keyData);
        } catch (BadCertTemplateException e) {
            throw e;
        } catch (Exception e) {
            LOG.debug("populateFromPubKeyInfo", e);
            throw new BadCertTemplateException("invalid public key: " + e.getMessage());
        }
        return publicKey;
    } else if (keyParamsOption instanceof RSAParametersOption) {
        RSAParametersOption rsaOption = (RSAParametersOption) keyParamsOption;

        ASN1Integer modulus;
        try {
            ASN1Sequence seq = ASN1Sequence.getInstance(publicKey.getPublicKeyData().getBytes());
            modulus = ASN1Integer.getInstance(seq.getObjectAt(0));
        } catch (IllegalArgumentException e) {
            throw new BadCertTemplateException("invalid publicKeyData");
        }

        int modulusLength = modulus.getPositiveValue().bitLength();
        if ((rsaOption.allowsModulusLength(modulusLength))) {
            return publicKey;
        }
    } else if (keyParamsOption instanceof DSAParametersOption) {
        DSAParametersOption dsaOption = (DSAParametersOption) keyParamsOption;
        ASN1Encodable params = publicKey.getAlgorithm().getParameters();
        if (params == null) {
            throw new BadCertTemplateException("null Dss-Parms is not permitted");
        }

        int pLength;
        int qLength;

        try {
            ASN1Sequence seq = ASN1Sequence.getInstance(params);
            ASN1Integer p = ASN1Integer.getInstance(seq.getObjectAt(0));
            ASN1Integer q = ASN1Integer.getInstance(seq.getObjectAt(1));
            pLength = p.getPositiveValue().bitLength();
            qLength = q.getPositiveValue().bitLength();
        } catch (IllegalArgumentException | ArrayIndexOutOfBoundsException e) {
            throw new BadCertTemplateException("illegal Dss-Parms");
        }

        boolean match = dsaOption.allowsPLength(pLength);
        if (match) {
            match = dsaOption.allowsQLength(qLength);
        }

        if (match) {
            return publicKey;
        }
    } else {
        throw new RuntimeException("should not reach here, unknown KeyParametersOption " + keyParamsOption);
    }

    throw new BadCertTemplateException("the given publicKey is not permitted");
}

From source file:org.xipki.ca.client.impl.CmpRequestor.java

License:Open Source License

protected ASN1Encodable extractXipkiActionContent(final ASN1Encodable itvValue, final int action)
        throws CmpRequestorException {
    ASN1Sequence seq;/*ww  w.j  a v  a  2s .c  om*/
    try {
        seq = ASN1Sequence.getInstance(itvValue);
    } catch (IllegalArgumentException e) {
        throw new CmpRequestorException("invalid syntax of the response");
    }
    int n = seq.size();
    if (n != 1 && n != 2) {
        throw new CmpRequestorException("invalid syntax of the response");
    }

    int _action;
    try {
        _action = ASN1Integer.getInstance(seq.getObjectAt(0)).getPositiveValue().intValue();
    } catch (IllegalArgumentException e) {
        throw new CmpRequestorException("invalid syntax of the response");
    }

    if (action != _action) {
        throw new CmpRequestorException(
                "received XiPKI action '" + _action + "' instead the exceptected '" + action + "'");
    }

    return (n == 1) ? null : seq.getObjectAt(1);
}