List of usage examples for org.bouncycastle.asn1 ASN1InputStream ASN1InputStream
public ASN1InputStream(byte[] input)
From source file:org.candlepin.pki.impl.BouncyCastlePKIUtility.java
License:Open Source License
@Override public String decodeDERValue(byte[] value) { ASN1InputStream vis = null;/*from w w w .jav a2s. c o m*/ ASN1InputStream decoded = null; try { vis = new ASN1InputStream(value); decoded = new ASN1InputStream(((DEROctetString) vis.readObject()).getOctets()); return decoded.readObject().toString(); } catch (IOException e) { throw new RuntimeException(e); } finally { if (vis != null) { try { vis.close(); } catch (IOException e) { log.warn("failed to close ASN1 stream", e); } } if (decoded != null) { try { decoded.close(); } catch (IOException e) { log.warn("failed to close ASN1 stream", e); } } } }
From source file:org.candlepin.util.X509CRLStreamWriter.java
License:Open Source License
public synchronized X509CRLStreamWriter preScan(InputStream crlToChange, CRLEntryValidator validator) throws IOException { if (locked) { throw new IllegalStateException("Cannot modify a locked stream."); }//from ww w . j a va2s.c o m if (preScanned) { throw new IllegalStateException("preScan has already been run."); } X509CRLEntryStream reaperStream = null; ASN1InputStream asn1In = null; try { reaperStream = new X509CRLEntryStream(crlToChange); try { if (!reaperStream.hasNext()) { emptyCrl = true; preScanned = true; return this; } while (reaperStream.hasNext()) { X509CRLEntryObject entry = reaperStream.next(); if (validator != null && validator.shouldDelete(entry)) { deletedEntries.add(entry.getSerialNumber()); deletedEntriesLength += entry.getEncoded().length; } } } catch (CRLException e) { throw new IOException("Could not read CRL entry", e); } /* At this point, crlToChange is at the point where the crlExtensions would * be. RFC 5280 says that "Conforming CRL issuers are REQUIRED to include * the authority key identifier (Section 5.2.1) and the CRL number (Section 5.2.3) * extensions in all CRLs issued. */ byte[] oldExtensions = null; DERObject o; asn1In = new ASN1InputStream(crlToChange); while ((o = asn1In.readObject()) != null) { if (o instanceof DERSequence) { // Now we are at the signatureAlgorithm DERSequence seq = (DERSequence) o; if (seq.getObjectAt(0) instanceof DERObjectIdentifier) { signingAlg = new AlgorithmIdentifier(seq); digestAlg = new DefaultDigestAlgorithmIdentifierFinder().find(signingAlg); try { // Build the signer this.signer = new RSADigestSigner(createDigest(digestAlg)); signer.init(true, new RSAKeyParameters(true, key.getModulus(), key.getPrivateExponent())); } catch (CryptoException e) { throw new IOException( "Could not create RSADigest signer for " + digestAlg.getAlgorithm()); } } } else if (o instanceof DERBitString) { oldSigLength = o.getDEREncoded().length; } else { if (oldExtensions != null) { throw new IllegalStateException("Already read in CRL extensions."); } oldExtensions = ((DERTaggedObject) o).getDEREncoded(); } } if (oldExtensions == null) { /* v1 CRLs (defined in RFC 1422) don't require extensions but all new * CRLs should be v2 (defined in RFC 5280). In the extremely unlikely * event that someone is working with a v1 CRL, we handle it here although * we print a warning. */ preScanned = true; newExtensions = null; extensionsDelta = 0; log.warn("The CRL you are modifying is a version 1 CRL." + " Please investigate moving to a version 2 CRL by adding the CRL Number" + " and Authority Key Identifier extensions."); return this; } newExtensions = updateExtensions(oldExtensions); extensionsDelta = (newExtensions.length - oldExtensions.length) + findHeaderBytesDelta(oldExtensions.length, newExtensions.length); } finally { if (reaperStream != null) { reaperStream.close(); } IOUtils.closeQuietly(asn1In); } preScanned = true; return this; }
From source file:org.candlepin.util.X509CRLStreamWriter.java
License:Open Source License
protected void writeToEmptyCrl(OutputStream out) throws IOException { ASN1InputStream asn1in = null; try {/* w w w .j a va2 s.co m*/ asn1in = new ASN1InputStream(crlIn); DERSequence certListSeq = (DERSequence) asn1in.readObject(); CertificateList certList = new CertificateList(certListSeq); X509CRLHolder oldCrl = new X509CRLHolder(certList); X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(oldCrl.getIssuer(), new Date()); crlBuilder.addCRL(oldCrl); Date now = new Date(); Date oldNextUpdate = certList.getNextUpdate().getDate(); Date oldThisUpdate = certList.getThisUpdate().getDate(); Date nextUpdate = new Date(now.getTime() + (oldNextUpdate.getTime() - oldThisUpdate.getTime())); crlBuilder.setNextUpdate(nextUpdate); for (Object o : oldCrl.getExtensionOIDs()) { ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) o; X509Extension ext = oldCrl.getExtension(oid); if (oid.equals(X509Extension.cRLNumber)) { DEROctetString octet = (DEROctetString) ext.getValue().getDERObject(); DERInteger currentNumber = (DERInteger) DERTaggedObject.fromByteArray(octet.getOctets()); DERInteger nextNumber = new DERInteger(currentNumber.getValue().add(BigInteger.ONE)); crlBuilder.addExtension(oid, ext.isCritical(), nextNumber); } else if (oid.equals(X509Extension.authorityKeyIdentifier)) { crlBuilder.addExtension(oid, ext.isCritical(), new AuthorityKeyIdentifierStructure(ext.getValue().getDEREncoded())); } } for (DERSequence entry : newEntries) { // XXX: This is all a bit messy considering the user already passed in the serial, date // and reason. BigInteger serial = ((DERInteger) entry.getObjectAt(0)).getValue(); Date revokeDate = ((Time) entry.getObjectAt(1)).getDate(); int reason = CRLReason.unspecified; if (entry.size() == 3) { X509Extensions extensions = (X509Extensions) entry.getObjectAt(2); X509Extension reasonExt = extensions.getExtension(X509Extension.reasonCode); if (reasonExt != null) { reason = ((DEREnumerated) reasonExt.getParsedValue()).getValue().intValue(); } } crlBuilder.addCRLEntry(serial, revokeDate, reason); } RSAKeyParameters keyParams = new RSAKeyParameters(true, key.getModulus(), key.getPrivateExponent()); signingAlg = oldCrl.toASN1Structure().getSignatureAlgorithm(); digestAlg = new DefaultDigestAlgorithmIdentifierFinder().find(signingAlg); ContentSigner s; try { s = new BcRSAContentSignerBuilder(signingAlg, digestAlg).build(keyParams); X509CRLHolder newCrl = crlBuilder.build(s); out.write(newCrl.getEncoded()); } catch (OperatorCreationException e) { throw new IOException("Could not sign CRL", e); } } finally { IOUtils.closeQuietly(asn1in); } }
From source file:org.ccnx.ccn.impl.security.crypto.util.CryptoUtil.java
License:Open Source License
/** * Helper function to decode DER content. * @param decodable content to decode/*w ww . j a v a 2 s. c om*/ * @return generic DERObject, result of decoding * @throws CertificateEncodingException if there is a problem decoding the content */ public static DERObject decode(byte[] decodable) throws CertificateEncodingException { DERObject dobj = null; try { ByteArrayInputStream bais = new ByteArrayInputStream(decodable); ASN1InputStream dis = new ASN1InputStream(bais); dobj = dis.readObject(); dis.close(); } catch (IOException ex) { StringBuffer sb = new StringBuffer(); sb.append("decode error - length " + decodable.length); for (byte b : decodable) sb.append(" " + Integer.toHexString((int) b)); Log.severe(sb.toString()); for (StackTraceElement ste : ex.getStackTrace()) Log.severe(ste.toString()); throw new CertificateEncodingException("Cannot encode: " + ex.toString()); } return dobj; }
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 a2s.c om*/ * 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 v a 2s .c o m * * @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 *///w w w. j a va 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) *//* w ww . j a v a 2s.c om*/ @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//w w w . j av a 2 s.c o m * * @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);/* w w w. j a va 2s.c om*/ 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()); }