Example usage for org.bouncycastle.asn1 DERSequence DERSequence

List of usage examples for org.bouncycastle.asn1 DERSequence DERSequence

Introduction

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

Prototype

public DERSequence(ASN1Encodable[] elements) 

Source Link

Document

Create a sequence containing an array of objects.

Usage

From source file:org.italiangrid.voms.asn1.VOMSACGenerator.java

License:Apache License

public CertificateExtension generateVOMSExtension(List<X509AttributeCertificateHolder> acs) {

    ASN1EncodableVector vomsACs = new ASN1EncodableVector();

    for (X509AttributeCertificateHolder ac : acs)
        vomsACs.add(ac.toASN1Structure());

    DERSequence acSeq = new DERSequence(vomsACs);

    CertificateExtension ext = new CertificateExtension(VOMS_EXTENSION_OID.getId(), acSeq.toASN1Object(),
            false);/*from   w  w w.ja  v  a  2 s .c o m*/

    return ext;
}

From source file:org.jboss.as.test.integration.security.common.negotiation.KerberosTestUtils.java

License:Open Source License

/**
 * Generates SPNEGO init token with given initial ticket and supported mechanisms.
 *
 * @param ticket initial ticket for the preferred (the first) mechanism.
 * @param supMechOids object identifiers (OIDs) of supported mechanisms for the SPNEGO.
 * @return ASN.1 encoded SPNEGO init token
 *//*from w  ww  . ja  v a 2s  .  c o  m*/
public static byte[] generateSpnegoTokenInit(byte[] ticket, String... supMechOids) throws IOException {
    DEROctetString ticketForPreferredMech = new DEROctetString(ticket);

    ASN1EncodableVector mechSeq = new ASN1EncodableVector();
    for (String mech : supMechOids) {
        mechSeq.add(new ASN1ObjectIdentifier(mech));
    }
    DERTaggedObject taggedMechTypes = new DERTaggedObject(0, new DERSequence(mechSeq));
    DERTaggedObject taggedMechToken = new DERTaggedObject(2, ticketForPreferredMech);
    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(taggedMechTypes);
    v.add(taggedMechToken);
    DERSequence seqNegTokenInit = new DERSequence(v);
    DERTaggedObject taggedSpnego = new DERTaggedObject(0, seqNegTokenInit);

    ASN1EncodableVector appVec = new ASN1EncodableVector();
    appVec.add(new ASN1ObjectIdentifier(OID_SPNEGO));
    appVec.add(taggedSpnego);
    DERApplicationSpecific app = new DERApplicationSpecific(0, appVec);
    return app.getEncoded();
}

From source file:org.jboss.as.test.integration.security.common.negotiation.KerberosTestUtils.java

License:Open Source License

/**
 * Generates SPNEGO response (to a "select mechanism challenge") with given bytes as the ticket for selected mechanism.
 *
 * @param ticket//from  ww w  .j  a v a  2  s  . c om
 * @return ASN.1 encoded SPNEGO response
 */
public static byte[] generateSpnegoTokenResp(byte[] ticket) throws IOException {
    DEROctetString ourKerberosTicket = new DEROctetString(ticket);

    DERTaggedObject taggedNegState = new DERTaggedObject(0, new ASN1Enumerated(1)); // accept-incomplete
    DERTaggedObject taggedResponseToken = new DERTaggedObject(2, ourKerberosTicket);
    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(taggedNegState);
    v.add(taggedResponseToken);
    DERSequence seqNegTokenResp = new DERSequence(v);
    DERTaggedObject taggedSpnego = new DERTaggedObject(1, seqNegTokenResp);
    return taggedSpnego.getEncoded();
}

From source file:org.jivesoftware.util.CertificateManager.java

License:Open Source License

/**
 * Creates an X509 version3 certificate.
 *
 * @param kp           KeyPair that keeps the public and private keys for the new certificate.
 * @param months       time to live//ww w .ja  va  2  s .  c o m
 * @param issuerDN     Issuer string e.g "O=Grid,OU=OGSA,CN=ACME"
 * @param subjectDN    Subject string e.g "O=Grid,OU=OGSA,CN=John Doe"
 * @param domain       Domain of the server.
 * @param signAlgoritm Signature algorithm. This can be either a name or an OID.
 * @return X509 V3 Certificate
 * @throws GeneralSecurityException
 * @throws IOException
 */
private static synchronized X509Certificate createX509V3Certificate(KeyPair kp, int months, String issuerDN,
        String subjectDN, String domain, String signAlgoritm) throws GeneralSecurityException, IOException {
    PublicKey pubKey = kp.getPublic();
    PrivateKey privKey = kp.getPrivate();

    byte[] serno = new byte[8];
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
    random.setSeed((new Date().getTime()));
    random.nextBytes(serno);
    BigInteger serial = (new java.math.BigInteger(serno)).abs();

    X509V3CertificateGenerator certGenerator = new X509V3CertificateGenerator();
    certGenerator.reset();

    certGenerator.setSerialNumber(serial);
    certGenerator.setIssuerDN(new X509Name(issuerDN));
    certGenerator.setNotBefore(new Date(System.currentTimeMillis()));
    certGenerator.setNotAfter(new Date(System.currentTimeMillis() + months * (1000L * 60 * 60 * 24 * 30)));
    certGenerator.setSubjectDN(new X509Name(subjectDN));
    certGenerator.setPublicKey(pubKey);
    certGenerator.setSignatureAlgorithm(signAlgoritm);

    // Generate the subject alternative name
    boolean critical = subjectDN == null || "".equals(subjectDN.trim());
    ASN1Sequence othernameSequence = new DERSequence(
            new ASN1Encodable[] { new DERObjectIdentifier("1.3.6.1.5.5.7.8.5"),
                    new DERTaggedObject(true, 0, new DERUTF8String(domain)) });
    GeneralName othernameGN = new GeneralName(GeneralName.otherName, othernameSequence);
    GeneralNames subjectAltNames = new GeneralNames(new GeneralName[] { othernameGN });
    // Add subject alternative name extension
    certGenerator.addExtension(X509Extensions.SubjectAlternativeName, critical, subjectAltNames);

    X509Certificate cert = certGenerator.generateX509Certificate(privKey, "BC", new SecureRandom());
    cert.checkValidity(new Date());
    cert.verify(pubKey);

    return cert;
}

From source file:org.jmrtd.Passport.java

License:Open Source License

/**
 * Check the active authentication result.
 * /*from  w w  w  . ja v a  2s  . c  om*/
 * @param aaResult
 * @return
 */
public boolean verifyAA(ActiveAuthenticationResult aaResult) {
    try {
        PublicKey publicKey = aaResult.getPublicKey();
        String digestAlgorithm = aaResult.getDigestAlgorithm();
        String signatureAlgorithm = aaResult.getSignatureAlgorithm();
        byte[] challenge = aaResult.getChallenge();
        byte[] response = aaResult.getResponse();

        String pubKeyAlgorithm = publicKey.getAlgorithm();
        if ("RSA".equals(pubKeyAlgorithm)) {
            /* FIXME: check that digestAlgorithm = "SHA1" in this case, check (and re-initialize) rsaAASignature (and rsaAACipher). */
            if (!"SHA1".equalsIgnoreCase(digestAlgorithm) || !"SHA-1".equalsIgnoreCase(digestAlgorithm)
                    || !"SHA1WithRSA/ISO9796-2".equalsIgnoreCase(signatureAlgorithm)) {
                LOGGER.warning("Unexpected algorithms for RSA AA: " + "digest algorithm = "
                        + (digestAlgorithm == null ? "null" : digestAlgorithm) + ", signature algorithm = "
                        + (signatureAlgorithm == null ? "null" : signatureAlgorithm));

                rsaAADigest = MessageDigest
                        .getInstance(digestAlgorithm); /* NOTE: for output length measurement only. -- MO */
                rsaAASignature = Signature.getInstance(signatureAlgorithm, BC_PROVIDER);
            }

            RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
            rsaAACipher.init(Cipher.DECRYPT_MODE, rsaPublicKey);
            rsaAASignature.initVerify(rsaPublicKey);

            int digestLength = rsaAADigest.getDigestLength(); /* SHA1 should be 20 bytes = 160 bits */
            assert (digestLength == 20);
            byte[] plaintext = rsaAACipher.doFinal(response);
            byte[] m1 = Util.recoverMessage(digestLength, plaintext);
            rsaAASignature.update(m1);
            rsaAASignature.update(challenge);
            boolean success = rsaAASignature.verify(response);

            if (success) {
                verificationStatus.setAA(VerificationStatus.Verdict.SUCCEEDED, ReasonCode.SIGNATURE_CHECKED,
                        aaResult);
            } else {
                verificationStatus.setAA(VerificationStatus.Verdict.FAILED, ReasonCode.SIGNATURE_FAILURE,
                        aaResult);
            }
            return success;
        } else if ("EC".equals(pubKeyAlgorithm) || "ECDSA".equals(pubKeyAlgorithm)) {
            ECPublicKey ecdsaPublicKey = (ECPublicKey) publicKey;

            if (ecdsaAASignature == null || signatureAlgorithm != null
                    && !signatureAlgorithm.equals(ecdsaAASignature.getAlgorithm())) {
                LOGGER.warning(
                        "Re-initializing ecdsaAASignature with signature algorithm " + signatureAlgorithm);
                ecdsaAASignature = Signature.getInstance(signatureAlgorithm);
            }
            if (ecdsaAADigest == null
                    || digestAlgorithm != null && !digestAlgorithm.equals(ecdsaAADigest.getAlgorithm())) {
                LOGGER.warning("Re-initializing ecdsaAADigest with digest algorithm " + digestAlgorithm);
                ecdsaAADigest = MessageDigest.getInstance(digestAlgorithm);
            }

            ecdsaAASignature.initVerify(ecdsaPublicKey);

            if (response.length % 2 != 0) {
                LOGGER.warning("Active Authentication response is not of even length");
            }

            int l = response.length / 2;
            BigInteger r = Util.os2i(response, 0, l);
            BigInteger s = Util.os2i(response, l, l);

            ecdsaAASignature.update(challenge);

            try {

                ASN1Sequence asn1Sequence = new DERSequence(
                        new ASN1Encodable[] { new ASN1Integer(r), new ASN1Integer(s) });
                boolean success = ecdsaAASignature.verify(asn1Sequence.getEncoded());
                if (success) {
                    verificationStatus.setAA(VerificationStatus.Verdict.SUCCEEDED, ReasonCode.SUCCEEDED,
                            aaResult);
                } else {
                    verificationStatus.setAA(VerificationStatus.Verdict.FAILED, ReasonCode.SIGNATURE_FAILURE,
                            aaResult);
                }
                return success;
            } catch (IOException ioe) {
                LOGGER.severe("Unexpected exception during AA signature verification with ECDSA");
                ioe.printStackTrace();
                verificationStatus.setAA(VerificationStatus.Verdict.FAILED,
                        ReasonCode.UNEXPECTED_EXCEPTION_FAILURE, aaResult);
                return false;
            }
        } else {
            LOGGER.severe("Unsupported AA public key type " + publicKey.getClass().getSimpleName());
            verificationStatus.setAA(VerificationStatus.Verdict.FAILED, ReasonCode.UNSUPPORTED_KEY_TYPE_FAILURE,
                    aaResult);
            return false;
        }
    } catch (Exception e) {
        verificationStatus.setAA(VerificationStatus.Verdict.FAILED, ReasonCode.UNEXPECTED_EXCEPTION_FAILURE,
                aaResult);
        return false;
    }
}

From source file:org.jnotary.dvcs.Data.java

License:Open Source License

@Override
public ASN1Primitive toASN1Primitive() {
    if (message != null)
        return message.toASN1Primitive();
    if (messageImprint != null)
        return messageImprint.toASN1Primitive();
    if (certs != null) {
        ASN1EncodableVector seq = new ASN1EncodableVector();
        for (int i = 0; i < certs.length; i++) {
            seq.add(certs[i]);/*from w ww  . ja v a  2  s  .c om*/
        }
        return new DERSequence(seq).toASN1Primitive();
    }
    return null;
}

From source file:org.jnotary.dvcs.DVCSCertInfo.java

License:Open Source License

@Override
public ASN1Primitive toASN1Primitive() {
    ASN1EncodableVector v = new ASN1EncodableVector();

    if (version != null)
        v.add(version);/*from   ww  w. java  2  s .co  m*/
    v.add(dvReqInfo);
    v.add(messageImprint);
    v.add(serialNumber);
    v.add(responseTime);

    if (getDvStatus() != null)
        v.add(new DERTaggedObject(true, 0, getDvStatus()));
    if (getPolicy() != null)
        v.add(new DERTaggedObject(true, 1, getPolicy()));
    if (getReqSignature() != null)
        v.add(new DERTaggedObject(true, 2, getReqSignature()));
    if (getCerts() != null && getCerts().length > 0) {
        ASN1EncodableVector seq = new ASN1EncodableVector();
        for (int i = 0; i < getCerts().length; i++) {
            seq.add(getCerts()[i].toASN1Primitive());
        }
        v.add(new DERTaggedObject(true, 3, new DERSequence(seq)));
    }
    if (getExtensions() != null)
        v.add(getExtensions());

    return new DERSequence(v);
}

From source file:org.jnotary.dvcs.DVCSErrorNotice.java

License:Open Source License

@Override
public ASN1Primitive toASN1Primitive() {
    ASN1EncodableVector v = new ASN1EncodableVector();

    v.add(transactionStatus);//from   www  . j a  va 2 s  .  com
    if (transactionIdentifier != null)
        v.add(transactionIdentifier);

    return new DERSequence(v);
}

From source file:org.jnotary.dvcs.DVCSRequest.java

License:Open Source License

@Override
public ASN1Primitive toASN1Primitive() {
    ASN1EncodableVector v = new ASN1EncodableVector();

    v.add(requestInformation);/*from   w w  w  .j  a  v a2s.c  o m*/
    v.add(data);

    if (transactionIdentifier != null)
        v.add(transactionIdentifier);

    return new DERSequence(v);
}

From source file:org.jnotary.dvcs.DVCSRequestInformation.java

License:Open Source License

@Override
public ASN1Primitive toASN1Primitive() {
    ASN1EncodableVector v = new ASN1EncodableVector();

    if (version != null)
        v.add(version);//  www  . ja  va  2  s.c om
    v.add(service);

    if (nonce != null)
        v.add(nonce);
    if (requestTime != null)
        v.add(requestTime);
    if (requester != null)
        v.add(new DERTaggedObject(true, 0, requester));
    if (requestPolicy != null)
        v.add(new DERTaggedObject(true, 1, requestPolicy));
    if (dvcs != null)
        v.add(new DERTaggedObject(true, 2, dvcs));
    if (dataLocations != null)
        v.add(new DERTaggedObject(true, 3, dataLocations));
    if (extensions != null)
        v.add(new DERTaggedObject(false, 4, extensions));

    return new DERSequence(v);
}