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.ccnx.ccn.impl.security.crypto.util.CryptoUtil.java

License:Open Source License

/**
 * Helper method to pull SubjectAlternativeNames from a certificate. BouncyCastle has
 * one of these, but it isn't included on all platforms. We get one by default from X509Certificate
 * but it returns us a collection of ? and we can't ever know what the ? is because we might
 * get a different impl class on different platforms. So we have to roll our own.
 * //from w  w w.j a v a 2s  .c o m
 * We filter the general names down to ones we can handle.
 * @param certificate
 * @return
 * @throws IOException 
 * @throws CertificateEncodingException 
 */
public static ArrayList<Tuple<Integer, String>> getSubjectAlternativeNames(X509Certificate certificate)
        throws IOException, CertificateEncodingException {

    byte[] encodedExtension = certificate.getExtensionValue(X509Extensions.SubjectAlternativeName.getId());

    ArrayList<Tuple<Integer, String>> list = new ArrayList<Tuple<Integer, String>>();

    if (null == encodedExtension) {
        return list;
    }

    // content of extension is wrapped in a DEROctetString
    DEROctetString content = (DEROctetString) CryptoUtil.decode(encodedExtension);
    byte[] encapsulatedOctetString = content.getOctets();

    ASN1InputStream aIn = new ASN1InputStream(encapsulatedOctetString);
    ASN1Encodable decodedObject = (ASN1Encodable) aIn.readObject();
    ASN1Sequence sequence = (ASN1Sequence) decodedObject.getDERObject();

    Integer tag;
    GeneralName generalName;

    Enumeration<?> it = sequence.getObjects();
    while (it.hasMoreElements()) {
        generalName = GeneralName.getInstance(it.nextElement());
        tag = generalName.getTagNo();

        switch (tag) {
        case GeneralName.dNSName:
        case GeneralName.rfc822Name:
        case GeneralName.uniformResourceIdentifier:
            list.add(new Tuple<Integer, String>(tag, ((DERString) generalName.getName()).getString()));
        default:
            // ignore other types
        }
    }
    return list;
}

From source file:org.ccnx.ccn.impl.security.crypto.util.SignatureHelper.java

License:Open Source License

/**
 * Gets an AlgorithmIdentifier incorporating a given digest and
 * encryption algorithm, and containing any necessary parameters for
 * the signing key.//from  w  ww.ja  va 2s  .  c om
 * 
 * @param hashAlgorithm the JCA standard name of the digest algorithm
 * (e.g. "SHA1")
 * @param signingKey the private key that will be used to compute the
 * signature
 * @return the algorithm identifier.
 * @throws NoSuchAlgorithmException if the algorithm identifier can't
 * be formed
 * @throws InvalidParameterSpecException
 * @throws InvalidAlgorithmParameterException
 */
public static AlgorithmIdentifier getSignatureAlgorithm(String hashAlgorithm, Key signingKey)
        throws NoSuchAlgorithmException, InvalidParameterSpecException, InvalidAlgorithmParameterException {
    String signatureAlgorithmOID = getSignatureAlgorithmOID(hashAlgorithm, signingKey.getAlgorithm());

    if (signatureAlgorithmOID == null) {
        if (Log.isLoggable(Level.WARNING)) {
            Log.warning("Error: got no signature algorithm!");
        }
        throw new NoSuchAlgorithmException("Cannot determine OID for hash algorithm " + hashAlgorithm
                + " and encryption alg " + signingKey.getAlgorithm());
    }

    AlgorithmIdentifier thisSignatureAlgorithm = null;
    try {

        DEREncodable paramData = null;
        AlgorithmParameters params = OIDLookup.getParametersFromKey(signingKey);

        if (params == null) {
            paramData = new DERUnknownTag(DERTags.NULL, new byte[0]);
        } else {
            ByteArrayInputStream bais = new ByteArrayInputStream(params.getEncoded());
            ASN1InputStream dis = new ASN1InputStream(bais);
            paramData = dis.readObject();
        }

        // Now we need the OID and the parameters. This is not the most
        // efficient way in the world to do this, but it should work.
        thisSignatureAlgorithm = new AlgorithmIdentifier(new DERObjectIdentifier(signatureAlgorithmOID),
                paramData);
    } catch (IOException ex) {
        System.out.println("This should not happen: getSignatureAlgorithm -- ");
        System.out.println("    IOException thrown when decoding a key");
        ex.getMessage();
        ex.printStackTrace();
        throw new InvalidParameterSpecException(ex.getMessage());
    }
    return thisSignatureAlgorithm;
}

From source file:org.ccnx.ccn.impl.security.keystore.AESKeyStoreSpi.java

License:Open Source License

/**
 * Load in the key from the keystore file
 *//*from w  w w .j av  a 2  s . co m*/
@Override
public void engineLoad(InputStream stream, char[] password)
        throws IOException, NoSuchAlgorithmException, CertificateException {
    if (null == stream)
        return;
    if (null != _id)
        return; // We already have the key so don't need to reload it
    ASN1InputStream ais = new ASN1InputStream(stream);
    DERSequence ds = (DERSequence) ais.readObject();
    DERInteger version = (DERInteger) ds.getObjectAt(0);
    if (version.getValue().intValue() != VERSION)
        throw new IOException("Unsupported AESKeyStore version: " + version.getValue().intValue());
    _oid = (DERObjectIdentifier) ds.getObjectAt(1);
    String keyAlgorithm = OIDLookup.getDigestName(_oid.toString());
    int aeslen = keyAlgorithmToCipherSize(keyAlgorithm);
    ASN1OctetString os = (ASN1OctetString) ds.getObjectAt(2);
    byte[] cryptoData = os.getOctets();
    int checkLength = cryptoData.length - (IV_SIZE + aeslen);
    if (checkLength <= 0)
        throw new IOException("Corrupted keystore");
    byte[] iv = new byte[IV_SIZE];
    System.arraycopy(cryptoData, 0, iv, 0, iv.length);
    Tuple<SecretKeySpec, SecretKeySpec> keys = initializeForAES(password);
    try {
        Cipher cipher = Cipher.getInstance(AES_CRYPTO_ALGORITHM);
        IvParameterSpec ivspec = new IvParameterSpec(iv);
        cipher.init(Cipher.DECRYPT_MODE, keys.first(), ivspec);
        byte[] cryptBytes = new byte[aeslen];
        System.arraycopy(cryptoData, IV_SIZE, cryptBytes, 0, cryptBytes.length);
        _id = cipher.doFinal(cryptBytes);
        byte[] checkbuf = new byte[IV_SIZE + cryptBytes.length];
        System.arraycopy(iv, 0, checkbuf, 0, IV_SIZE);
        System.arraycopy(cryptBytes, 0, checkbuf, IV_SIZE, cryptBytes.length);
        byte[] check = new byte[checkLength];
        System.arraycopy(cryptoData, IV_SIZE + aeslen, check, 0, checkLength);
        _macKeyMac.init(keys.second());
        byte[] hmac = _macKeyMac.doFinal(checkbuf);
        if (!Arrays.equals(hmac, check))
            throw new IOException("Bad signature in AES keystore");
    } catch (Exception e) {
        throw new IOException(e);
    }
}

From source file:org.certificateservices.custom.c2x.its.crypto.DefaultCryptoManager.java

License:Open Source License

/**
 * @see org.certificateservices.custom.c2x.its.crypto.CryptoManager#signMessage(byte[], PublicKeyAlgorithm,  PrivateKey)
 *///from  w  ww  .j a  v a  2 s.co m
@Override
public Signature signMessage(byte[] message, PublicKeyAlgorithm alg, PrivateKey privateKey)
        throws IllegalArgumentException, SignatureException, IOException {

    ASN1InputStream asn1InputStream = null;
    try {
        byte[] messageDigest = digest(message, alg);

        java.security.Signature signature = java.security.Signature.getInstance("NONEwithECDSA", provider);
        signature.initSign(privateKey);
        signature.update(messageDigest);
        byte[] dERSignature = signature.sign();

        ByteArrayInputStream inStream = new ByteArrayInputStream(dERSignature);
        asn1InputStream = new ASN1InputStream(inStream);

        DLSequence dLSequence = (DLSequence) asn1InputStream.readObject();
        BigInteger r = ((ASN1Integer) dLSequence.getObjectAt(0)).getPositiveValue();
        BigInteger s = ((ASN1Integer) dLSequence.getObjectAt(1)).getPositiveValue();

        ByteArrayOutputStream baos = new ByteArrayOutputStream(alg.getFieldSize());
        SerializationHelper.writeFixedFieldSizeKey(alg, baos, s);

        return new Signature(alg, new EcdsaSignature(alg, new EccPoint(alg, EccPointType.x_coordinate_only, r),
                baos.toByteArray()));

    } catch (Exception e) {
        if (e instanceof IllegalArgumentException) {
            throw (IllegalArgumentException) e;
        }
        if (e instanceof IOException) {
            throw (IOException) e;
        }
        if (e instanceof SignatureException) {
            throw (SignatureException) e;
        }

        throw new SignatureException(
                "Internal error generating signature " + e.getClass().getSimpleName() + ": " + e.getMessage(),
                e);

    } finally {
        if (asn1InputStream != null) {
            asn1InputStream.close();
        }
    }
}

From source file:org.cesecore.certificates.ca.X509CA.java

License:Open Source License

/**
 * Generate a CRL or a deltaCRL/*  www . j a  va2s . c om*/
 * 
 * @param certs
 *            list of revoked certificates
 * @param crlnumber
 *            CRLNumber for this CRL
 * @param isDeltaCRL
 *            true if we should generate a DeltaCRL
 * @param basecrlnumber
 *            caseCRLNumber for a delta CRL, use 0 for full CRLs
 * @param certProfile
 *            certificate profile for CRL Distribution point in the CRL, or null
 * @return CRL
 * @throws CryptoTokenOfflineException
 * @throws IllegalCryptoTokenException
 * @throws IOException
 * @throws SignatureException
 * @throws NoSuchProviderException
 * @throws InvalidKeyException
 * @throws CRLException
 * @throws NoSuchAlgorithmException
 */
private X509CRLHolder generateCRL(CryptoToken cryptoToken, Collection<RevokedCertInfo> certs, long crlPeriod,
        int crlnumber, boolean isDeltaCRL, int basecrlnumber)
        throws CryptoTokenOfflineException, IllegalCryptoTokenException, IOException, SignatureException,
        NoSuchProviderException, InvalidKeyException, CRLException, NoSuchAlgorithmException {
    final String sigAlg = getCAInfo().getCAToken().getSignatureAlgorithm();

    if (log.isDebugEnabled()) {
        log.debug("generateCRL(" + certs.size() + ", " + crlPeriod + ", " + crlnumber + ", " + isDeltaCRL + ", "
                + basecrlnumber);
    }

    // Make DNs
    final X509Certificate cacert = (X509Certificate) getCACertificate();
    final X500Name issuer;
    if (cacert == null) {
        // This is an initial root CA, since no CA-certificate exists
        // (I don't think we can ever get here!!!)
        final X500NameStyle nameStyle;
        if (getUsePrintableStringSubjectDN()) {
            nameStyle = PrintableStringNameStyle.INSTANCE;
        } else {
            nameStyle = CeSecoreNameStyle.INSTANCE;
        }
        issuer = CertTools.stringToBcX500Name(getSubjectDN(), nameStyle, getUseLdapDNOrder());
    } else {
        issuer = X500Name.getInstance(cacert.getSubjectX500Principal().getEncoded());
    }
    final Date thisUpdate = new Date();
    final Date nextUpdate = new Date();
    nextUpdate.setTime(nextUpdate.getTime() + crlPeriod);
    final X509v2CRLBuilder crlgen = new X509v2CRLBuilder(issuer, thisUpdate);
    crlgen.setNextUpdate(nextUpdate);
    if (certs != null) {
        if (log.isDebugEnabled()) {
            log.debug("Adding " + certs.size() + " revoked certificates to CRL. Free memory="
                    + Runtime.getRuntime().freeMemory());
        }
        final Iterator<RevokedCertInfo> it = certs.iterator();
        while (it.hasNext()) {
            final RevokedCertInfo certinfo = (RevokedCertInfo) it.next();
            crlgen.addCRLEntry(certinfo.getUserCertificate(), certinfo.getRevocationDate(),
                    certinfo.getReason());
        }
        if (log.isDebugEnabled()) {
            log.debug("Finished adding " + certs.size() + " revoked certificates to CRL. Free memory="
                    + Runtime.getRuntime().freeMemory());
        }
    }

    // Authority key identifier
    if (getUseAuthorityKeyIdentifier() == true) {
        byte[] caSkid = (cacert != null ? CertTools.getSubjectKeyId(cacert) : null);
        if (caSkid != null) {
            // Use subject key id from CA certificate
            AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(caSkid);
            crlgen.addExtension(Extension.authorityKeyIdentifier, getAuthorityKeyIdentifierCritical(), aki);
        } else {
            // Generate from SHA1 of public key
            ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(cryptoToken
                    .getPublicKey(getCAToken().getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CRLSIGN))
                    .getEncoded()));
            try {
                SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo(
                        (ASN1Sequence) asn1InputStream.readObject());
                AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki);
                crlgen.addExtension(Extension.authorityKeyIdentifier, getAuthorityKeyIdentifierCritical(), aki);
            } finally {
                asn1InputStream.close();
            }
        }
    }

    // Authority Information Access  
    final ASN1EncodableVector accessList = new ASN1EncodableVector();
    if (getAuthorityInformationAccess() != null) {
        for (String url : getAuthorityInformationAccess()) {
            if (StringUtils.isNotEmpty(url)) {
                GeneralName accessLocation = new GeneralName(GeneralName.uniformResourceIdentifier,
                        new DERIA5String(url));
                accessList.add(new AccessDescription(AccessDescription.id_ad_caIssuers, accessLocation));
            }
        }
    }
    if (accessList.size() > 0) {
        AuthorityInformationAccess authorityInformationAccess = AuthorityInformationAccess
                .getInstance(new DERSequence(accessList));
        // "This CRL extension MUST NOT be marked critical." according to rfc4325
        crlgen.addExtension(Extension.authorityInfoAccess, false, authorityInformationAccess);
    }

    // CRLNumber extension
    if (getUseCRLNumber() == true) {
        CRLNumber crlnum = new CRLNumber(BigInteger.valueOf(crlnumber));
        crlgen.addExtension(Extension.cRLNumber, this.getCRLNumberCritical(), crlnum);
    }

    if (isDeltaCRL) {
        // DeltaCRLIndicator extension
        CRLNumber basecrlnum = new CRLNumber(BigInteger.valueOf(basecrlnumber));
        crlgen.addExtension(Extension.deltaCRLIndicator, true, basecrlnum);
    }
    // CRL Distribution point URI and Freshest CRL DP
    if (getUseCrlDistributionPointOnCrl()) {
        String crldistpoint = getDefaultCRLDistPoint();
        List<DistributionPoint> distpoints = generateDistributionPoints(crldistpoint);

        if (distpoints.size() > 0) {
            IssuingDistributionPoint idp = new IssuingDistributionPoint(
                    distpoints.get(0).getDistributionPoint(), false, false, null, false, false);

            // According to the RFC, IDP must be a critical extension.
            // Nonetheless, at the moment, Mozilla is not able to correctly
            // handle the IDP extension and discards the CRL if it is critical.
            crlgen.addExtension(Extension.issuingDistributionPoint, getCrlDistributionPointOnCrlCritical(),
                    idp);
        }

        if (!isDeltaCRL) {
            String crlFreshestDP = getCADefinedFreshestCRL();
            List<DistributionPoint> freshestDistPoints = generateDistributionPoints(crlFreshestDP);
            if (freshestDistPoints.size() > 0) {
                CRLDistPoint ext = new CRLDistPoint((DistributionPoint[]) freshestDistPoints
                        .toArray(new DistributionPoint[freshestDistPoints.size()]));

                // According to the RFC, the Freshest CRL extension on a
                // CRL must not be marked as critical. Therefore it is
                // hardcoded as not critical and is independent of
                // getCrlDistributionPointOnCrlCritical().
                crlgen.addExtension(Extension.freshestCRL, false, ext);
            }

        }
    }

    final X509CRLHolder crl;
    if (log.isDebugEnabled()) {
        log.debug("Signing CRL. Free memory=" + Runtime.getRuntime().freeMemory());
    }
    final String alias = getCAToken().getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CRLSIGN);
    try {
        final ContentSigner signer = new BufferingContentSigner(new JcaContentSignerBuilder(sigAlg)
                .setProvider(cryptoToken.getSignProviderName()).build(cryptoToken.getPrivateKey(alias)), 20480);
        crl = crlgen.build(signer);
    } catch (OperatorCreationException e) {
        // Very fatal error
        throw new RuntimeException("Can not create Jca content signer: ", e);
    }
    if (log.isDebugEnabled()) {
        log.debug("Finished signing CRL. Free memory=" + Runtime.getRuntime().freeMemory());
    }

    // Verify using the CA certificate before returning
    // If we can not verify the issued CRL using the CA certificate we don't want to issue this CRL
    // because something is wrong...
    final PublicKey verifyKey;
    if (cacert != null) {
        verifyKey = cacert.getPublicKey();
        if (log.isTraceEnabled()) {
            log.trace("Got the verify key from the CA certificate.");
        }
    } else {
        verifyKey = cryptoToken.getPublicKey(alias);
        if (log.isTraceEnabled()) {
            log.trace("Got the verify key from the CA token.");
        }
    }
    try {
        final ContentVerifierProvider verifier = new JcaContentVerifierProviderBuilder().build(verifyKey);
        if (!crl.isSignatureValid(verifier)) {
            throw new SignatureException("Error verifying CRL to be returned.");
        }
    } catch (OperatorCreationException e) {
        // Very fatal error
        throw new RuntimeException("Can not create Jca content signer: ", e);
    } catch (CertException e) {
        throw new SignatureException(e.getMessage(), e);
    }
    if (log.isDebugEnabled()) {
        log.debug("Returning CRL. Free memory=" + Runtime.getRuntime().freeMemory());
    }
    return crl;
}

From source file:org.cesecore.certificates.ca.X509CATest.java

License:Open Source License

@SuppressWarnings("unchecked")
private void doTestX509CABasicOperations(String algName) throws Exception {
    final CryptoToken cryptoToken = getNewCryptoToken();
    final X509CA x509ca = createTestCA(cryptoToken, CADN);
    Certificate cacert = x509ca.getCACertificate();

    // Start by creating a PKCS7
    byte[] p7 = x509ca.createPKCS7(cryptoToken, cacert, true);
    assertNotNull(p7);/*from www.  ja v  a 2 s.  c o m*/
    CMSSignedData s = new CMSSignedData(p7);
    Store certstore = s.getCertificates();
    Collection<X509CertificateHolder> certs = certstore.getMatches(null);
    assertEquals(2, certs.size());
    p7 = x509ca.createPKCS7(cryptoToken, cacert, false);
    assertNotNull(p7);
    s = new CMSSignedData(p7);
    certstore = s.getCertificates();
    certs = certstore.getMatches(null);
    assertEquals(1, certs.size());

    // Create a certificate request (will be pkcs10)
    byte[] req = x509ca.createRequest(cryptoToken, null, algName, cacert,
            CATokenConstants.CAKEYPURPOSE_CERTSIGN);
    PKCS10CertificationRequest p10 = new PKCS10CertificationRequest(req);
    assertNotNull(p10);
    String dn = p10.getSubject().toString();
    assertEquals(CADN, dn);

    // Make a request with some pkcs11 attributes as well
    Collection<ASN1Encodable> attributes = new ArrayList<ASN1Encodable>();
    // Add a subject alternative name
    ASN1EncodableVector altnameattr = new ASN1EncodableVector();
    altnameattr.add(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
    GeneralNames san = CertTools.getGeneralNamesFromAltName("dNSName=foobar.bar.com");
    ExtensionsGenerator extgen = new ExtensionsGenerator();
    extgen.addExtension(Extension.subjectAlternativeName, false, san);
    Extensions exts = extgen.generate();
    altnameattr.add(new DERSet(exts));
    // Add a challenge password as well
    ASN1EncodableVector pwdattr = new ASN1EncodableVector();
    pwdattr.add(PKCSObjectIdentifiers.pkcs_9_at_challengePassword);
    ASN1EncodableVector pwdvalues = new ASN1EncodableVector();
    pwdvalues.add(new DERUTF8String("foobar123"));
    pwdattr.add(new DERSet(pwdvalues));
    attributes.add(new DERSequence(altnameattr));
    attributes.add(new DERSequence(pwdattr));
    // create the p10
    req = x509ca.createRequest(cryptoToken, attributes, algName, cacert,
            CATokenConstants.CAKEYPURPOSE_CERTSIGN);
    p10 = new PKCS10CertificationRequest(req);
    assertNotNull(p10);
    dn = p10.getSubject().toString();
    assertEquals(CADN, dn);
    Attribute[] attrs = p10.getAttributes();
    assertEquals(2, attrs.length);
    PKCS10RequestMessage p10msg = new PKCS10RequestMessage(new JcaPKCS10CertificationRequest(p10));
    assertEquals("foobar123", p10msg.getPassword());
    assertEquals("dNSName=foobar.bar.com", p10msg.getRequestAltNames());

    try {
        x509ca.createAuthCertSignRequest(cryptoToken, p10.getEncoded());
    } catch (UnsupportedOperationException e) {
        // Expected for a X509 CA
    }

    // Generate a client certificate and check that it was generated correctly
    EndEntityInformation user = new EndEntityInformation("username", "CN=User", 666, "rfc822Name=user@user.com",
            "user@user.com", new EndEntityType(EndEntityTypes.ENDUSER), 0, 0, EndEntityConstants.TOKEN_USERGEN,
            0, null);
    KeyPair keypair = genTestKeyPair(algName);
    CertificateProfile cp = new CertificateProfile(CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
    cp.addCertificatePolicy(new CertificatePolicy("1.1.1.2", null, null));
    cp.setUseCertificatePolicies(true);
    Certificate usercert = x509ca.generateCertificate(cryptoToken, user, keypair.getPublic(), 0, null, 10L, cp,
            "00000");
    assertNotNull(usercert);
    assertEquals("CN=User", CertTools.getSubjectDN(usercert));
    assertEquals(CADN, CertTools.getIssuerDN(usercert));
    assertEquals(getTestKeyPairAlgName(algName).toUpperCase(),
            AlgorithmTools.getCertSignatureAlgorithmNameAsString(usercert).toUpperCase());
    assertEquals(new String(CertTools.getSubjectKeyId(cacert)),
            new String(CertTools.getAuthorityKeyId(usercert)));
    assertEquals("user@user.com", CertTools.getEMailAddress(usercert));
    assertEquals("rfc822name=user@user.com", CertTools.getSubjectAlternativeName(usercert));
    assertNull(CertTools.getUPNAltName(usercert));
    assertFalse(CertTools.isSelfSigned(usercert));
    usercert.verify(cryptoToken
            .getPublicKey(x509ca.getCAToken().getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN)));
    usercert.verify(x509ca.getCACertificate().getPublicKey());
    assertTrue(CertTools.isCA(x509ca.getCACertificate()));
    assertFalse(CertTools.isCA(usercert));
    assertEquals("1.1.1.2", CertTools.getCertificatePolicyId(usercert, 0));
    X509Certificate cert = (X509Certificate) usercert;
    boolean[] ku = cert.getKeyUsage();
    assertTrue(ku[0]);
    assertTrue(ku[1]);
    assertTrue(ku[2]);
    assertFalse(ku[3]);
    assertFalse(ku[4]);
    assertFalse(ku[5]);
    assertFalse(ku[6]);
    assertFalse(ku[7]);
    int bcku = CertTools.sunKeyUsageToBC(ku);
    assertEquals(X509KeyUsage.digitalSignature | X509KeyUsage.nonRepudiation | X509KeyUsage.keyEncipherment,
            bcku);

    // Create a CRL
    Collection<RevokedCertInfo> revcerts = new ArrayList<RevokedCertInfo>();
    X509CRLHolder crl = x509ca.generateCRL(cryptoToken, revcerts, 1);
    assertNotNull(crl);
    X509CRL xcrl = CertTools.getCRLfromByteArray(crl.getEncoded());
    assertEquals(CADN, CertTools.getIssuerDN(xcrl));
    Set<?> set = xcrl.getRevokedCertificates();
    assertNull(set);
    BigInteger num = CrlExtensions.getCrlNumber(xcrl);
    assertEquals(1, num.intValue());
    BigInteger deltanum = CrlExtensions.getDeltaCRLIndicator(xcrl);
    assertEquals(-1, deltanum.intValue());
    // Revoke some cert
    Date revDate = new Date();
    revcerts.add(new RevokedCertInfo(CertTools.getFingerprintAsString(usercert).getBytes(),
            CertTools.getSerialNumber(usercert).toByteArray(), revDate.getTime(),
            RevokedCertInfo.REVOCATION_REASON_CERTIFICATEHOLD, CertTools.getNotAfter(usercert).getTime()));
    crl = x509ca.generateCRL(cryptoToken, revcerts, 2);
    assertNotNull(crl);
    xcrl = CertTools.getCRLfromByteArray(crl.getEncoded());
    set = xcrl.getRevokedCertificates();
    assertEquals(1, set.size());
    num = CrlExtensions.getCrlNumber(xcrl);
    assertEquals(2, num.intValue());
    X509CRLEntry entry = (X509CRLEntry) set.iterator().next();
    assertEquals(CertTools.getSerialNumber(usercert).toString(), entry.getSerialNumber().toString());
    assertEquals(revDate.toString(), entry.getRevocationDate().toString());
    // Getting the revocation reason is a pita...
    byte[] extval = entry.getExtensionValue(Extension.reasonCode.getId());
    ASN1InputStream aIn = new ASN1InputStream(new ByteArrayInputStream(extval));
    ASN1OctetString octs = (ASN1OctetString) aIn.readObject();
    aIn = new ASN1InputStream(new ByteArrayInputStream(octs.getOctets()));
    ASN1Primitive obj = aIn.readObject();
    CRLReason reason = CRLReason.getInstance((ASN1Enumerated) obj);
    assertEquals("CRLReason: certificateHold", reason.toString());
    //DEROctetString ostr = (DEROctetString)obj;

    // Create a delta CRL
    revcerts = new ArrayList<RevokedCertInfo>();
    crl = x509ca.generateDeltaCRL(cryptoToken, revcerts, 3, 2);
    assertNotNull(crl);
    xcrl = CertTools.getCRLfromByteArray(crl.getEncoded());
    assertEquals(CADN, CertTools.getIssuerDN(xcrl));
    set = xcrl.getRevokedCertificates();
    assertNull(set);
    num = CrlExtensions.getCrlNumber(xcrl);
    assertEquals(3, num.intValue());
    deltanum = CrlExtensions.getDeltaCRLIndicator(xcrl);
    assertEquals(2, deltanum.intValue());
    revcerts.add(new RevokedCertInfo(CertTools.getFingerprintAsString(usercert).getBytes(),
            CertTools.getSerialNumber(usercert).toByteArray(), revDate.getTime(),
            RevokedCertInfo.REVOCATION_REASON_CERTIFICATEHOLD, CertTools.getNotAfter(usercert).getTime()));
    crl = x509ca.generateDeltaCRL(cryptoToken, revcerts, 4, 3);
    assertNotNull(crl);
    xcrl = CertTools.getCRLfromByteArray(crl.getEncoded());
    deltanum = CrlExtensions.getDeltaCRLIndicator(xcrl);
    assertEquals(3, deltanum.intValue());
    set = xcrl.getRevokedCertificates();
    assertEquals(1, set.size());
    entry = (X509CRLEntry) set.iterator().next();
    assertEquals(CertTools.getSerialNumber(usercert).toString(), entry.getSerialNumber().toString());
    assertEquals(revDate.toString(), entry.getRevocationDate().toString());
    // Getting the revocation reason is a pita...
    extval = entry.getExtensionValue(Extension.reasonCode.getId());
    aIn = new ASN1InputStream(new ByteArrayInputStream(extval));
    octs = (ASN1OctetString) aIn.readObject();
    aIn = new ASN1InputStream(new ByteArrayInputStream(octs.getOctets()));
    obj = aIn.readObject();
    reason = CRLReason.getInstance((ASN1Enumerated) obj);
    assertEquals("CRLReason: certificateHold", reason.toString());
}

From source file:org.cesecore.certificates.ca.X509CATest.java

License:Open Source License

/**
 * Tests the extension CRL Distribution Point on CRLs
 * // w  w w . java 2s.  c  o m
 */
@Test
public void testCRLDistPointOnCRL() throws Exception {
    final CryptoToken cryptoToken = getNewCryptoToken();
    final X509CA ca = createTestCA(cryptoToken, CADN);

    final String cdpURL = "http://www.ejbca.org/foo/bar.crl";
    X509CAInfo cainfo = (X509CAInfo) ca.getCAInfo();

    cainfo.setUseCrlDistributionPointOnCrl(true);
    cainfo.setDefaultCRLDistPoint(cdpURL);
    ca.updateCA(cryptoToken, cainfo);

    Collection<RevokedCertInfo> revcerts = new ArrayList<RevokedCertInfo>();
    X509CRLHolder crl = ca.generateCRL(cryptoToken, revcerts, 1);
    assertNotNull(crl);
    X509CRL xcrl = CertTools.getCRLfromByteArray(crl.getEncoded());

    byte[] cdpDER = xcrl.getExtensionValue(Extension.issuingDistributionPoint.getId());
    assertNotNull("CRL has no distribution points", cdpDER);

    ASN1InputStream aIn = new ASN1InputStream(new ByteArrayInputStream(cdpDER));
    ASN1OctetString octs = (ASN1OctetString) aIn.readObject();
    aIn = new ASN1InputStream(new ByteArrayInputStream(octs.getOctets()));
    IssuingDistributionPoint cdp = IssuingDistributionPoint.getInstance((ASN1Sequence) aIn.readObject());
    DistributionPointName distpoint = cdp.getDistributionPoint();

    assertEquals("CRL distribution point is different", cdpURL,
            ((DERIA5String) ((GeneralNames) distpoint.getName()).getNames()[0].getName()).getString());

    cainfo.setUseCrlDistributionPointOnCrl(false);
    cainfo.setDefaultCRLDistPoint(null);
    ca.updateCA(cryptoToken, cainfo);
    crl = ca.generateCRL(cryptoToken, revcerts, 1);
    assertNotNull(crl);
    xcrl = CertTools.getCRLfromByteArray(crl.getEncoded());
    assertNull("CRL has distribution points", xcrl.getExtensionValue(Extension.cRLDistributionPoints.getId()));
}

From source file:org.cesecore.certificates.ca.X509CATest.java

License:Open Source License

/**
 * Tests the extension Freshest CRL DP./*from  ww w  . j  a  va  2 s  .  co  m*/
 * 
 * @throws Exception
 *             in case of error.
 */
@Test
public void testCRLFreshestCRL() throws Exception {
    final CryptoToken cryptoToken = getNewCryptoToken();
    final X509CA ca = createTestCA(cryptoToken, CADN);
    final String cdpURL = "http://www.ejbca.org/foo/bar.crl";
    final String freshestCdpURL = "http://www.ejbca.org/foo/delta.crl";
    X509CAInfo cainfo = (X509CAInfo) ca.getCAInfo();

    cainfo.setUseCrlDistributionPointOnCrl(true);
    cainfo.setDefaultCRLDistPoint(cdpURL);
    cainfo.setCADefinedFreshestCRL(freshestCdpURL);
    ca.updateCA(cryptoToken, cainfo);

    Collection<RevokedCertInfo> revcerts = new ArrayList<RevokedCertInfo>();
    X509CRLHolder crl = ca.generateCRL(cryptoToken, revcerts, 1);
    assertNotNull(crl);
    X509CRL xcrl = CertTools.getCRLfromByteArray(crl.getEncoded());

    byte[] cFreshestDpDER = xcrl.getExtensionValue(Extension.freshestCRL.getId());
    assertNotNull("CRL has no Freshest Distribution Point", cFreshestDpDER);

    ASN1InputStream aIn = new ASN1InputStream(new ByteArrayInputStream(cFreshestDpDER));
    ASN1OctetString octs = (ASN1OctetString) aIn.readObject();
    aIn = new ASN1InputStream(new ByteArrayInputStream(octs.getOctets()));
    CRLDistPoint cdp = CRLDistPoint.getInstance((ASN1Sequence) aIn.readObject());
    DistributionPoint[] distpoints = cdp.getDistributionPoints();

    assertEquals("More CRL Freshest distributions points than expected", 1, distpoints.length);
    assertEquals("Freshest CRL distribution point is different", freshestCdpURL,
            ((DERIA5String) ((GeneralNames) distpoints[0].getDistributionPoint().getName()).getNames()[0]
                    .getName()).getString());

    cainfo.setUseCrlDistributionPointOnCrl(false);
    cainfo.setDefaultCRLDistPoint(null);
    cainfo.setCADefinedFreshestCRL(null);
    ca.updateCA(cryptoToken, cainfo);

    crl = ca.generateCRL(cryptoToken, revcerts, 1);
    assertNotNull(crl);
    xcrl = CertTools.getCRLfromByteArray(crl.getEncoded());
    assertNull("CRL has freshest crl extension", xcrl.getExtensionValue(Extension.freshestCRL.getId()));
}

From source file:org.cesecore.certificates.ca.X509CATest.java

License:Open Source License

/** 
 * Test that the CA can issue certificates with custom certificate extensions.
 *//*  w w w. j a  v a 2s .  c  o m*/
@Test
public void testCustomCertificateExtension() throws Exception {
    final CryptoToken cryptoToken = getNewCryptoToken();
    X509CA testCa = createTestCA(cryptoToken, "CN=foo");
    Collection<RevokedCertInfo> revcerts = new ArrayList<RevokedCertInfo>();
    X509CRLHolder testCrl = testCa.generateCRL(cryptoToken, revcerts, 0);
    assertNotNull(testCrl);
    X509CRL xcrl = CertTools.getCRLfromByteArray(testCrl.getEncoded());
    Collection<String> result = CertTools.getAuthorityInformationAccess(xcrl);
    assertEquals("A list was returned without any values present.", 0, result.size());
    // Issue a certificate with two different basic certificate extensions
    EndEntityInformation user = new EndEntityInformation("username", "CN=User", 666, "rfc822Name=user@user.com",
            "user@user.com", new EndEntityType(EndEntityTypes.ENDUSER), 0, 0, EndEntityConstants.TOKEN_USERGEN,
            0, null);
    CertificateProfile cp = new CertificateProfile(CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
    // Configure some custom basic certificate extension
    // one with a good IA5String encoding
    Properties prop = new Properties();
    prop.put("id1.oid", "2.16.840.1.113730.1.13");
    prop.put("id1.classpath", "org.cesecore.certificates.certificate.certextensions.BasicCertificateExtension");
    prop.put("id1.displayname", "NetscapeComment");
    prop.put("id1.used", "true");
    prop.put("id1.translatable", "false");
    prop.put("id1.critical", "false");
    prop.put("id1.property.encoding", "DERIA5STRING");
    prop.put("id1.property.dynamin", "false");
    prop.put("id1.property.value", "Hello World");
    // one RAW with proper DER encoding
    prop.put("id2.oid", "1.2.3.4");
    prop.put("id2.classpath", "org.cesecore.certificates.certificate.certextensions.BasicCertificateExtension");
    prop.put("id2.displayname", "RawProper");
    prop.put("id2.used", "true");
    prop.put("id2.translatable", "false");
    prop.put("id2.critical", "false");
    prop.put("id2.property.encoding", "RAW");
    prop.put("id2.property.dynamin", "false");
    prop.put("id2.property.value", "301a300c060a2b060104018237140202300a06082b06010505070302");
    // one RAW with no DER encoding (actually invalid according to RFC5280)
    prop.put("id3.oid", "1.2.3.5");
    prop.put("id3.classpath", "org.cesecore.certificates.certificate.certextensions.BasicCertificateExtension");
    prop.put("id3.displayname", "RawNoDer");
    prop.put("id3.used", "true");
    prop.put("id3.translatable", "false");
    prop.put("id3.critical", "false");
    prop.put("id3.property.encoding", "RAW");
    prop.put("id3.property.dynamin", "false");
    prop.put("id3.property.value", "aabbccddeeff00");
    // Load the Custom extensions
    Field certificateExtensionFactoryInstance = CertificateExtensionFactory.class.getDeclaredField("instance");
    certificateExtensionFactoryInstance.setAccessible(true);
    Method parseConfiguration = CertificateExtensionFactory.class.getDeclaredMethod("parseConfiguration",
            Properties.class);
    parseConfiguration.setAccessible(true);
    CertificateExtensionFactory instance = (CertificateExtensionFactory) parseConfiguration.invoke(null, prop);
    certificateExtensionFactoryInstance.set(null, instance);
    CertificateExtensionFactory fact = CertificateExtensionFactory.getInstance();
    assertEquals(fact.getCertificateExtensions(1).getOID(), "2.16.840.1.113730.1.13");
    assertEquals(fact.getCertificateExtensions(2).getOID(), "1.2.3.4");
    assertEquals(fact.getCertificateExtensions(3).getOID(), "1.2.3.5");
    // Configure to use the custom extensions in the certificate profile
    List<Integer> list = new ArrayList<Integer>();
    list.add(1);
    list.add(2);
    list.add(3);
    cp.setUsedCertificateExtensions(list);
    final KeyPair keypair = KeyTools.genKeys("512", "RSA");
    X509Certificate cert = (X509Certificate) testCa.generateCertificate(cryptoToken, user, keypair.getPublic(),
            0, null, 10L, cp, "00000");
    assertNotNull("A certificate should have been issued", cert);
    byte[] ext1 = cert.getExtensionValue("2.16.840.1.113730.1.13");
    // The Extension value is an Octet String, containing my value
    ASN1InputStream is = new ASN1InputStream(ext1);
    ASN1OctetString oct = (ASN1OctetString) (is.readObject());
    is.close();
    ASN1InputStream is2 = new ASN1InputStream(oct.getOctets());
    DERIA5String str = (DERIA5String) is2.readObject();
    is2.close();
    assertEquals("Hello World", str.getString());

    byte[] ext2 = cert.getExtensionValue("1.2.3.4");
    is = new ASN1InputStream(ext2);
    oct = (ASN1OctetString) (is.readObject());
    is.close();
    is2 = new ASN1InputStream(oct.getOctets());
    ASN1Sequence seq = (ASN1Sequence) is2.readObject();
    System.out.println(ASN1Dump.dumpAsString(seq));
    is2.close();
    ASN1Encodable enc = seq.getObjectAt(0);
    ASN1Sequence seq2 = ASN1Sequence.getInstance(enc);
    ASN1Encodable enc2 = seq2.getObjectAt(0);
    ASN1ObjectIdentifier id = ASN1ObjectIdentifier.getInstance(enc2);
    assertEquals("1.3.6.1.4.1.311.20.2.2", id.getId());
    enc = seq.getObjectAt(1);
    seq2 = ASN1Sequence.getInstance(enc);
    enc2 = seq2.getObjectAt(0);
    id = ASN1ObjectIdentifier.getInstance(enc2);
    assertEquals("1.3.6.1.5.5.7.3.2", id.getId());

    byte[] ext3 = cert.getExtensionValue("1.2.3.5");
    is = new ASN1InputStream(ext3);
    oct = (ASN1OctetString) (is.readObject());
    is.close();
    // This value can not be parsed as ASN.1
    byte[] bytes = oct.getOctets();
    assertEquals("aabbccddeeff00", Hex.toHexString(bytes));
}

From source file:org.cesecore.certificates.certificate.AvailableCustomCertExtensionsConfigTest.java

License:Open Source License

private ASN1Encodable getObject(byte[] valueEncoded) throws IOException {
    ASN1InputStream in = new ASN1InputStream(new ByteArrayInputStream(valueEncoded));
    try {/*from www  .  j ava2s .  c  om*/
        return in.readObject();
    } finally {
        in.close();
    }
}