List of usage examples for org.bouncycastle.asn1.x509 Extension keyUsage
ASN1ObjectIdentifier keyUsage
To view the source code for org.bouncycastle.asn1.x509 Extension keyUsage.
Click Source Link
From source file:org.cesecore.certificates.certificate.CertificateCreateSessionBean.java
License:Open Source License
@Override public CertificateResponseMessage createCertificate(final AuthenticationToken admin, final EndEntityInformation endEntityInformation, final CA ca, final RequestMessage req, final Class<? extends ResponseMessage> responseClass, CertificateGenerationParams certGenParams, final long updateTime) throws CryptoTokenOfflineException, SignRequestSignatureException, IllegalKeyException, IllegalNameException, CustomCertificateSerialNumberException, CertificateCreateException, CertificateRevokeException, CertificateSerialNumberException, AuthorizationDeniedException, IllegalValidityException, CAOfflineException, InvalidAlgorithmException, CertificateExtensionException { if (log.isTraceEnabled()) { log.trace(">createCertificate(IRequestMessage, CA)"); }// w w w .j ava 2 s.c om CertificateResponseMessage ret = null; try { final CAToken catoken = ca.getCAToken(); final CryptoToken cryptoToken = cryptoTokenManagementSession.getCryptoToken(catoken.getCryptoTokenId()); final String alias = catoken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN); // See if we need some key material to decrypt request if (req.requireKeyInfo()) { // You go figure...scep encrypts message with the public CA-cert req.setKeyInfo(ca.getCACertificate(), cryptoToken.getPrivateKey(alias), cryptoToken.getEncProviderName()); } // Verify the request final PublicKey reqpk; try { if (!req.verify()) { throw new SignRequestSignatureException( intres.getLocalizedMessage("createcert.popverificationfailed")); } reqpk = req.getRequestPublicKey(); if (reqpk == null) { final String msg = intres.getLocalizedMessage("createcert.nokeyinrequest"); throw new InvalidKeyException(msg); } } catch (InvalidKeyException e) { // If we get an invalid key exception here, we should throw an IllegalKeyException to the caller // The catch of InvalidKeyException in the end of this method, catches error from the CA crypto token throw new IllegalKeyException(e); } final Date notBefore = req.getRequestValidityNotBefore(); // Optionally requested validity final Date notAfter = req.getRequestValidityNotAfter(); // Optionally requested validity final Extensions exts = req.getRequestExtensions(); // Optionally requested extensions int keyusage = -1; if (exts != null) { if (log.isDebugEnabled()) { log.debug( "we have extensions, see if we can override KeyUsage by looking for a KeyUsage extension in request"); } final Extension ext = exts.getExtension(Extension.keyUsage); if (ext != null) { final ASN1OctetString os = ext.getExtnValue(); DERBitString bs; try { bs = new DERBitString(os.getEncoded()); } catch (IOException e) { throw new IllegalStateException("Unexpected IOException caught."); } keyusage = bs.intValue(); if (log.isDebugEnabled()) { log.debug("We have a key usage request extension: " + keyusage); } } } String sequence = null; byte[] ki = req.getRequestKeyInfo(); // CVC sequence is only 5 characters, don't fill with a lot of garbage here, it must be a readable string if ((ki != null) && (ki.length > 0) && (ki.length < 10)) { final String str = new String(ki); // A cvc sequence must be ascii printable, otherwise it's some binary data if (StringUtils.isAsciiPrintable(str)) { sequence = new String(ki); } } CertificateDataWrapper certWrapper = createCertificate(admin, endEntityInformation, ca, req, reqpk, keyusage, notBefore, notAfter, exts, sequence, certGenParams, updateTime); // Create the response message with all nonces and checks etc ret = ResponseMessageUtils.createResponseMessage(responseClass, req, ca.getCertificateChain(), cryptoToken.getPrivateKey(alias), cryptoToken.getEncProviderName()); ResponseStatus status = ResponseStatus.SUCCESS; FailInfo failInfo = null; String failText = null; if ((certWrapper == null) && (status == ResponseStatus.SUCCESS)) { status = ResponseStatus.FAILURE; failInfo = FailInfo.BAD_REQUEST; } else { ret.setCertificate(certWrapper.getCertificate()); ret.setCACert(ca.getCACertificate()); ret.setBase64CertData(certWrapper.getBase64CertData()); ret.setCertificateData(certWrapper.getCertificateData()); } ret.setStatus(status); if (failInfo != null) { ret.setFailInfo(failInfo); ret.setFailText(failText); } ret.create(); } catch (InvalidKeyException e) { throw new CertificateCreateException(e); } catch (NoSuchAlgorithmException e) { throw new CertificateCreateException(e); } catch (NoSuchProviderException e) { throw new CertificateCreateException(e); } catch (CertificateEncodingException e) { throw new CertificateCreateException(e); } catch (CRLException e) { throw new CertificateCreateException(e); } if (log.isTraceEnabled()) { log.trace("<createCertificate(IRequestMessage, CA)"); } return ret; }
From source file:org.cesecore.certificates.certificateprofile.CertificateProfileTest.java
License:Open Source License
@Test public void test06CertificateExtensions() throws Exception { CertificateProfile profile = new CertificateProfile(CertificateProfileConstants.CERTPROFILE_NO_PROFILE); // Check standard values for the certificate profile List<String> l = profile.getUsedStandardCertificateExtensions(); assertEquals(6, l.size());//from w ww.j av a2 s. c o m assertTrue(l.contains(Extension.keyUsage.getId())); assertTrue(l.contains(Extension.basicConstraints.getId())); assertTrue(l.contains(Extension.subjectKeyIdentifier.getId())); assertTrue(l.contains(Extension.authorityKeyIdentifier.getId())); assertTrue(l.contains(Extension.subjectAlternativeName.getId())); assertTrue(l.contains(Extension.issuerAlternativeName.getId())); CertificateProfile eprofile = new CertificateProfile(CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER); // Check standard values for the certificate profile l = eprofile.getUsedStandardCertificateExtensions(); assertEquals(7, l.size()); assertTrue(l.contains(Extension.keyUsage.getId())); assertTrue(l.contains(Extension.basicConstraints.getId())); assertTrue(l.contains(Extension.subjectKeyIdentifier.getId())); assertTrue(l.contains(Extension.authorityKeyIdentifier.getId())); assertTrue(l.contains(Extension.subjectAlternativeName.getId())); assertTrue(l.contains(Extension.issuerAlternativeName.getId())); assertTrue(l.contains(Extension.extendedKeyUsage.getId())); profile = new CertificateProfile(CertificateProfileConstants.CERTPROFILE_NO_PROFILE); profile.setUseAuthorityInformationAccess(true); profile.setUseCertificatePolicies(true); profile.setUseCRLDistributionPoint(true); profile.setUseFreshestCRL(true); profile.setUseMicrosoftTemplate(true); profile.setUseOcspNoCheck(true); profile.setUseQCStatement(true); profile.setUseExtendedKeyUsage(true); profile.setUseSubjectDirAttributes(true); l = profile.getUsedStandardCertificateExtensions(); assertEquals(15, l.size()); assertTrue(l.contains(Extension.keyUsage.getId())); assertTrue(l.contains(Extension.basicConstraints.getId())); assertTrue(l.contains(Extension.subjectKeyIdentifier.getId())); assertTrue(l.contains(Extension.authorityKeyIdentifier.getId())); assertTrue(l.contains(Extension.subjectAlternativeName.getId())); assertTrue(l.contains(Extension.issuerAlternativeName.getId())); assertTrue(l.contains(Extension.extendedKeyUsage.getId())); assertTrue(l.contains(Extension.authorityInfoAccess.getId())); assertTrue(l.contains(Extension.certificatePolicies.getId())); assertTrue(l.contains(Extension.cRLDistributionPoints.getId())); assertTrue(l.contains(Extension.freshestCRL.getId())); assertTrue(l.contains(OCSPObjectIdentifiers.id_pkix_ocsp_nocheck.getId())); assertTrue(l.contains(Extension.qCStatements.getId())); assertTrue(l.contains(Extension.subjectDirectoryAttributes.getId())); assertTrue(l.contains(CertTools.OID_MSTEMPLATE)); }
From source file:org.cesecore.certificates.crl.CrlCreateSessionTest.java
License:Open Source License
/** * Tests issuing a CRL from a CA with a SKID that is not generated with SHA1. * The CRL is checked to contain the correct AKID value. *//* www . java 2 s . co m*/ @Test public void testNonSHA1KeyId() throws Exception { final String subcaname = "CrlCSTestSub"; final String subcadn = "CN=" + subcaname; try { // Create an external root ca certificate final KeyPair rootcakp = KeyTools.genKeys("1024", "RSA"); final String rootcadn = "CN=CrlCSTestRoot"; final X509Certificate rootcacert = CertTools.genSelfCert(rootcadn, 3650, null, rootcakp.getPrivate(), rootcakp.getPublic(), AlgorithmConstants.SIGALG_SHA1_WITH_RSA, true, "BC", false); // Create sub ca final int cryptoTokenId = CryptoTokenTestUtils.createCryptoTokenForCA(authenticationToken, subcaname, "1024"); final CAToken catoken = CaTestUtils.createCaToken(cryptoTokenId, AlgorithmConstants.SIGALG_SHA1_WITH_RSA, AlgorithmConstants.SIGALG_SHA1_WITH_RSA); X509CAInfo subcainfo = new X509CAInfo(subcadn, subcaname, CAConstants.CA_ACTIVE, CertificateProfileConstants.CERTPROFILE_FIXED_SUBCA, 365, CAInfo.SIGNEDBYEXTERNALCA, null, catoken); X509CA subca = new X509CA(subcainfo); subca.setCAToken(catoken); caSession.addCA(authenticationToken, subca); // Issue sub CA certificate with a non-standard SKID PublicKey subcapubkey = cryptoTokenMgmtSession.getPublicKey(authenticationToken, cryptoTokenId, catoken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN)).getPublicKey(); Date firstDate = new Date(); firstDate.setTime(firstDate.getTime() - (10 * 60 * 1000)); Date lastDate = new Date(); lastDate.setTime(lastDate.getTime() + 365 * 24 * 60 * 60 * 1000); final SubjectPublicKeyInfo subcaspki = new SubjectPublicKeyInfo( (ASN1Sequence) ASN1Primitive.fromByteArray(subcapubkey.getEncoded())); final X509v3CertificateBuilder certbuilder = new X509v3CertificateBuilder( CertTools.stringToBcX500Name(rootcadn, false), new BigInteger(64, new Random(System.nanoTime())), firstDate, lastDate, CertTools.stringToBcX500Name(subcadn, false), subcaspki); final AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(CertTools.getAuthorityKeyId(rootcacert)); final SubjectKeyIdentifier ski = new SubjectKeyIdentifier(TEST_AKID); // Non-standard SKID. It should match the AKID in the CRL certbuilder.addExtension(Extension.authorityKeyIdentifier, true, aki); certbuilder.addExtension(Extension.subjectKeyIdentifier, false, ski); BasicConstraints bc = new BasicConstraints(true); certbuilder.addExtension(Extension.basicConstraints, true, bc); X509KeyUsage ku = new X509KeyUsage(X509KeyUsage.keyCertSign | X509KeyUsage.cRLSign); certbuilder.addExtension(Extension.keyUsage, true, ku); final ContentSigner signer = new BufferingContentSigner( new JcaContentSignerBuilder(AlgorithmConstants.SIGALG_SHA1_WITH_RSA) .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(rootcakp.getPrivate()), 20480); final X509CertificateHolder certHolder = certbuilder.build(signer); final X509Certificate subcacert = (X509Certificate) CertTools .getCertfromByteArray(certHolder.getEncoded(), "BC"); // Replace sub CA certificate with a sub CA cert containing the test AKID subcainfo = (X509CAInfo) caSession.getCAInfo(authenticationToken, subcaname); List<Certificate> certificatechain = new ArrayList<Certificate>(); certificatechain.add(subcacert); certificatechain.add(rootcacert); subcainfo.setCertificateChain(certificatechain); subcainfo.setExpireTime(CertTools.getNotAfter(subcacert)); caSession.editCA(authenticationToken, subcainfo); subca = (X509CA) caTestSessionRemote.getCA(authenticationToken, subcaname); assertArrayEquals("Wrong SKID in test CA.", TEST_AKID, CertTools.getSubjectKeyId(subca.getCACertificate())); // Create a base CRL and check the AKID int baseCrlNumber = crlStoreSession.getLastCRLNumber(subcadn, false) + 1; assertEquals("For a new CA, the next crl number should be 1.", 1, baseCrlNumber); crlCreateSession.generateAndStoreCRL(authenticationToken, subca, new ArrayList<RevokedCertInfo>(), -1, baseCrlNumber); final byte[] crl = crlStoreSession.getLastCRL(subcadn, false); checkCrlAkid(subca, crl); // Create a delta CRL and check the AKID int deltaCrlNumber = crlStoreSession.getLastCRLNumber(subcadn, false) + 1; assertEquals("Next CRL number should be 2 at this point.", 2, deltaCrlNumber); crlCreateSession.generateAndStoreCRL(authenticationToken, subca, new ArrayList<RevokedCertInfo>(), baseCrlNumber, deltaCrlNumber); final byte[] deltacrl = crlStoreSession.getLastCRL(subcadn, true); // true = get delta CRL checkCrlAkid(subca, deltacrl); } finally { // Remove everything created above to clean the database final Integer cryptoTokenId = cryptoTokenMgmtSession.getIdFromName(subcaname); if (cryptoTokenId != null) { CryptoTokenTestUtils.removeCryptoToken(authenticationToken, cryptoTokenId); } try { int caid = caSession.getCAInfo(authenticationToken, subcaname).getCAId(); // Delete sub CA CRLs while (true) { final byte[] crl = crlStoreSession.getLastCRL(subcadn, true); // delta CRLs if (crl == null) { break; } internalCertificateStoreSession.removeCRL(authenticationToken, CertTools.getFingerprintAsString(crl)); } while (true) { final byte[] crl = crlStoreSession.getLastCRL(subcadn, false); // base CRLs if (crl == null) { break; } internalCertificateStoreSession.removeCRL(authenticationToken, CertTools.getFingerprintAsString(crl)); } // Delete sub CA caSession.removeCA(authenticationToken, caid); } catch (CADoesntExistsException cade) { // NOPMD ignore } } }
From source file:org.cesecore.util.CertTools.java
License:Open Source License
public static X509Certificate genSelfCertForPurpose(String dn, long validity, String policyId, PrivateKey privKey, PublicKey pubKey, String sigAlg, boolean isCA, int keyusage, Date privateKeyNotBefore, Date privateKeyNotAfter, String provider, boolean ldapOrder, List<Extension> additionalExtensions) throws CertificateParsingException, IOException, OperatorCreationException { // Create self signed certificate Date firstDate = new Date(); // Set back startdate ten minutes to avoid some problems with wrongly set clocks. firstDate.setTime(firstDate.getTime() - (10 * 60 * 1000)); Date lastDate = new Date(); // validity in days = validity*24*60*60*1000 milliseconds lastDate.setTime(lastDate.getTime() + (validity * (24 * 60 * 60 * 1000))); // Transform the PublicKey to be sure we have it in a format that the X509 certificate generator handles, it might be // a CVC public key that is passed as parameter PublicKey publicKey = null;/*from w w w . j a va2 s. co m*/ if (pubKey instanceof RSAPublicKey) { RSAPublicKey rsapk = (RSAPublicKey) pubKey; RSAPublicKeySpec rSAPublicKeySpec = new RSAPublicKeySpec(rsapk.getModulus(), rsapk.getPublicExponent()); try { publicKey = KeyFactory.getInstance("RSA").generatePublic(rSAPublicKeySpec); } catch (InvalidKeySpecException e) { log.error("Error creating RSAPublicKey from spec: ", e); publicKey = pubKey; } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("RSA was not a known algorithm", e); } } else if (pubKey instanceof ECPublicKey) { ECPublicKey ecpk = (ECPublicKey) pubKey; try { ECPublicKeySpec ecspec = new ECPublicKeySpec(ecpk.getW(), ecpk.getParams()); // will throw NPE if key is "implicitlyCA" final String algo = ecpk.getAlgorithm(); if (algo.equals(AlgorithmConstants.KEYALGORITHM_ECGOST3410)) { try { publicKey = KeyFactory.getInstance("ECGOST3410").generatePublic(ecspec); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("ECGOST3410 was not a known algorithm", e); } } else if (algo.equals(AlgorithmConstants.KEYALGORITHM_DSTU4145)) { try { publicKey = KeyFactory.getInstance("DSTU4145").generatePublic(ecspec); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("DSTU4145 was not a known algorithm", e); } } else { try { publicKey = KeyFactory.getInstance("EC").generatePublic(ecspec); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("EC was not a known algorithm", e); } } } catch (InvalidKeySpecException e) { log.error("Error creating ECPublicKey from spec: ", e); publicKey = pubKey; } catch (NullPointerException e) { log.debug("NullPointerException, probably it is implicitlyCA generated keys: " + e.getMessage()); publicKey = pubKey; } } else { log.debug("Not converting key of class. " + pubKey.getClass().getName()); publicKey = pubKey; } // Serialnumber is random bits, where random generator is initialized with Date.getTime() when this // bean is created. byte[] serno = new byte[8]; SecureRandom random; try { random = SecureRandom.getInstance("SHA1PRNG"); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("SHA1PRNG was not a known algorithm", e); } random.setSeed(new Date().getTime()); random.nextBytes(serno); SubjectPublicKeyInfo pkinfo; try { pkinfo = new SubjectPublicKeyInfo((ASN1Sequence) ASN1Primitive.fromByteArray(publicKey.getEncoded())); } catch (IOException e) { throw new IllegalArgumentException("Provided public key could not be read to ASN1Primitive", e); } X509v3CertificateBuilder certbuilder = new X509v3CertificateBuilder( CertTools.stringToBcX500Name(dn, ldapOrder), new BigInteger(serno).abs(), firstDate, lastDate, CertTools.stringToBcX500Name(dn, ldapOrder), pkinfo); // Basic constranits is always critical and MUST be present at-least in CA-certificates. BasicConstraints bc = new BasicConstraints(isCA); certbuilder.addExtension(Extension.basicConstraints, true, bc); // Put critical KeyUsage in CA-certificates if (isCA || keyusage != 0) { X509KeyUsage ku = new X509KeyUsage(keyusage); certbuilder.addExtension(Extension.keyUsage, true, ku); } if ((privateKeyNotBefore != null) || (privateKeyNotAfter != null)) { final ASN1EncodableVector v = new ASN1EncodableVector(); if (privateKeyNotBefore != null) { v.add(new DERTaggedObject(false, 0, new DERGeneralizedTime(privateKeyNotBefore))); } if (privateKeyNotAfter != null) { v.add(new DERTaggedObject(false, 1, new DERGeneralizedTime(privateKeyNotAfter))); } certbuilder.addExtension(Extension.privateKeyUsagePeriod, false, new DERSequence(v)); } // Subject and Authority key identifier is always non-critical and MUST be present for certificates to verify in Firefox. try { if (isCA) { ASN1InputStream sAsn1InputStream = new ASN1InputStream( new ByteArrayInputStream(publicKey.getEncoded())); ASN1InputStream aAsn1InputStream = new ASN1InputStream( new ByteArrayInputStream(publicKey.getEncoded())); try { SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo( (ASN1Sequence) sAsn1InputStream.readObject()); X509ExtensionUtils x509ExtensionUtils = new BcX509ExtensionUtils(); SubjectKeyIdentifier ski = x509ExtensionUtils.createSubjectKeyIdentifier(spki); SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo( (ASN1Sequence) aAsn1InputStream.readObject()); AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki); certbuilder.addExtension(Extension.subjectKeyIdentifier, false, ski); certbuilder.addExtension(Extension.authorityKeyIdentifier, false, aki); } finally { sAsn1InputStream.close(); aAsn1InputStream.close(); } } } catch (IOException e) { // do nothing } // CertificatePolicies extension if supplied policy ID, always non-critical if (policyId != null) { PolicyInformation pi = new PolicyInformation(new ASN1ObjectIdentifier(policyId)); DERSequence seq = new DERSequence(pi); certbuilder.addExtension(Extension.certificatePolicies, false, seq); } // Add any additional if (additionalExtensions != null) { for (final Extension extension : additionalExtensions) { certbuilder.addExtension(extension.getExtnId(), extension.isCritical(), extension.getParsedValue()); } } final ContentSigner signer = new BufferingContentSigner( new JcaContentSignerBuilder(sigAlg).setProvider(provider).build(privKey), 20480); final X509CertificateHolder certHolder = certbuilder.build(signer); final X509Certificate selfcert = (X509Certificate) CertTools.getCertfromByteArray(certHolder.getEncoded()); return selfcert; }
From source file:org.conscrypt.java.security.TestKeyStore.java
License:Apache License
private static X509Certificate createCertificate(PublicKey publicKey, PrivateKey privateKey, X500Principal subject, X500Principal issuer, int keyUsage, boolean ca, List<KeyPurposeId> extendedKeyUsages, List<Boolean> criticalExtendedKeyUsages, List<GeneralName> subjectAltNames, List<GeneralSubtree> permittedNameConstraints, List<GeneralSubtree> excludedNameConstraints, BigInteger serialNumber) throws Exception { // Note that there is no way to programmatically make a // Certificate using java.* or javax.* APIs. The // CertificateFactory interface assumes you want to read // in a stream of bytes, typically the X.509 factory would // allow ASN.1 DER encoded bytes and optionally some PEM // formats. Here we use Bouncy Castle's // X509V3CertificateGenerator and related classes. long millisPerDay = 24 * 60 * 60 * 1000; long now = System.currentTimeMillis(); Date start = new Date(now - millisPerDay); Date end = new Date(now + millisPerDay); String keyAlgorithm = privateKey.getAlgorithm(); String signatureAlgorithm;/*from w w w .j a v a 2 s . c om*/ if (keyAlgorithm.equals("RSA")) { signatureAlgorithm = "sha256WithRSA"; } else if (keyAlgorithm.equals("DSA")) { signatureAlgorithm = "sha256WithDSA"; } else if (keyAlgorithm.equals("EC")) { signatureAlgorithm = "sha256WithECDSA"; } else if (keyAlgorithm.equals("EC_RSA")) { signatureAlgorithm = "sha256WithRSA"; } else { throw new IllegalArgumentException("Unknown key algorithm " + keyAlgorithm); } if (serialNumber == null) { byte[] serialBytes = new byte[16]; new SecureRandom().nextBytes(serialBytes); serialNumber = new BigInteger(1, serialBytes); } X509v3CertificateBuilder x509cg = new X509v3CertificateBuilder(X500Name.getInstance(issuer.getEncoded()), serialNumber, start, end, X500Name.getInstance(subject.getEncoded()), SubjectPublicKeyInfo.getInstance(publicKey.getEncoded())); if (keyUsage != 0) { x509cg.addExtension(Extension.keyUsage, true, new KeyUsage(keyUsage)); } if (ca) { x509cg.addExtension(Extension.basicConstraints, true, new BasicConstraints(true)); } for (int i = 0; i < extendedKeyUsages.size(); i++) { KeyPurposeId keyPurposeId = extendedKeyUsages.get(i); boolean critical = criticalExtendedKeyUsages.get(i); x509cg.addExtension(Extension.extendedKeyUsage, critical, new ExtendedKeyUsage(keyPurposeId)); } if (!subjectAltNames.isEmpty()) { x509cg.addExtension(Extension.subjectAlternativeName, false, new GeneralNames(subjectAltNames.toArray(new GeneralName[0])).getEncoded()); } if (!permittedNameConstraints.isEmpty() || !excludedNameConstraints.isEmpty()) { x509cg.addExtension(Extension.nameConstraints, true, new NameConstraints( permittedNameConstraints.toArray(new GeneralSubtree[permittedNameConstraints.size()]), excludedNameConstraints.toArray(new GeneralSubtree[excludedNameConstraints.size()]))); } X509CertificateHolder x509holder = x509cg .build(new JcaContentSignerBuilder(signatureAlgorithm).build(privateKey)); CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); X509Certificate x509c = (X509Certificate) certFactory .generateCertificate(new ByteArrayInputStream(x509holder.getEncoded())); if (StandardNames.IS_RI) { /* * The RI can't handle the BC EC signature algorithm * string of "ECDSA", since it expects "...WITHEC...", * so convert from BC to RI X509Certificate * implementation via bytes. */ CertificateFactory cf = CertificateFactory.getInstance("X.509"); ByteArrayInputStream bais = new ByteArrayInputStream(x509c.getEncoded()); Certificate c = cf.generateCertificate(bais); x509c = (X509Certificate) c; } return x509c; }
From source file:org.cryptable.pki.communication.PKICMPMessagesTest.java
License:Open Source License
/** * Check the extensions in the certification request * * @throws OperatorCreationException//from w ww . j a v a 2 s. c om * @throws PKICMPMessageException * @throws CertificateEncodingException * @throws IOException * @throws CRMFException * @throws CMPException * @throws CMSException */ @Test public void testCertificationWithExtensions() throws OperatorCreationException, PKICMPMessageException, CertificateEncodingException, IOException, CRMFException, CMPException, CMSException, NoSuchFieldException, IllegalAccessException { String distinguishedName = pki.getTestUser1Cert().getSubjectX500Principal().getName(); KeyPair keyPair = new KeyPair(pki.getTestUser1Cert().getPublicKey(), pki.getTestUser1CertPrivateKey()); List<Extension> extensionList = new ArrayList<Extension>(); // KeyUsage extensionList.add(new Extension(X509Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.nonRepudiation).getEncoded())); // Extended keyUsage List<KeyPurposeId> keyPurposeIds = new ArrayList<KeyPurposeId>(); keyPurposeIds.add(KeyPurposeId.getInstance(KeyPurposeId.id_kp_clientAuth)); keyPurposeIds.add(KeyPurposeId.getInstance(KeyPurposeId.id_kp_emailProtection)); extensionList.add(new Extension(X509Extension.extendedKeyUsage, false, new ExtendedKeyUsage(keyPurposeIds.toArray(new KeyPurposeId[keyPurposeIds.size()])).getEncoded())); // Subject alternative names List<GeneralName> generalNames = new ArrayList<GeneralName>(); generalNames.add(new GeneralName(GeneralName.dNSName, "www1.cryptable.org")); generalNames.add(new GeneralName(GeneralName.dNSName, "www2.cryptable.org")); GeneralNames subjectAlternativeName = new GeneralNames( generalNames.toArray(new GeneralName[generalNames.size()])); extensionList.add( new Extension(X509Extension.subjectAlternativeName, false, subjectAlternativeName.getEncoded())); PKICMPMessages pkiMessages = new PKICMPMessages(); pkiMessages.setPkiKeyStore(pkiKeyStoreRA); pkiMessages.setExtensions(extensionList.toArray(new Extension[extensionList.size()])); byte[] result = pkiMessages.createCertificateMessageWithLocalKey(distinguishedName, keyPair); ASN1InputStream asn1InputStream = new ASN1InputStream(result); ASN1Primitive asn1Primitive = asn1InputStream.readObject(); PKIMessage pkiMessage = PKIMessage.getInstance(asn1Primitive); CertReqMsg[] certReqMsgs = CertReqMessages.getInstance(pkiMessage.getBody().getContent()) .toCertReqMsgArray(); // KeyUsage KeyUsage verifyKeyUsage = KeyUsage.getInstance(certReqMsgs[0].getCertReq().getCertTemplate().getExtensions() .getExtensionParsedValue(Extension.keyUsage)); Assert.assertEquals(KeyUsage.digitalSignature | KeyUsage.nonRepudiation, verifyKeyUsage.getBytes()[0] & 0xFF); // Extended KeyUsage ExtendedKeyUsage verifyExtendedKeyUsage = ExtendedKeyUsage .fromExtensions(certReqMsgs[0].getCertReq().getCertTemplate().getExtensions()); Assert.assertTrue(verifyExtendedKeyUsage.hasKeyPurposeId(KeyPurposeId.id_kp_clientAuth)); Assert.assertTrue(verifyExtendedKeyUsage.hasKeyPurposeId(KeyPurposeId.id_kp_emailProtection)); // Subject Alternative Name GeneralNames verifyGeneralNames = GeneralNames.fromExtensions( certReqMsgs[0].getCertReq().getCertTemplate().getExtensions(), Extension.subjectAlternativeName); Assert.assertTrue(generalNames.contains(verifyGeneralNames.getNames()[0])); Assert.assertTrue(generalNames.contains(verifyGeneralNames.getNames()[1])); }
From source file:org.cryptable.pki.communication.PKICMPMessagesTest.java
License:Open Source License
/** * Test the confirmation message from the certification authority * * @throws IOException//from w w w .jav a 2s . co m * @throws CertificateEncodingException * @throws OperatorCreationException * @throws CMPException */ @Test public void testKeyUpdateWithLocalKeyWithExtensions() throws IOException, CertificateEncodingException, OperatorCreationException, CMPException, PKICMPMessageException, CRMFException, IllegalAccessException, CMSException, NoSuchFieldException { PKICMPMessages pkiMessages = new PKICMPMessages(); pkiMessages.setPkiKeyStore(pkiKeyStoreRA); KeyPair keyPair = new KeyPair(pki.getTestUser2Cert().getPublicKey(), pki.getTestUser2CertPrivateKey()); List<Extension> extensionList = new ArrayList<Extension>(); // KeyUsage extensionList.add(new Extension(X509Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.nonRepudiation).getEncoded())); // Extended keyUsage List<KeyPurposeId> keyPurposeIds = new ArrayList<KeyPurposeId>(); keyPurposeIds.add(KeyPurposeId.getInstance(KeyPurposeId.id_kp_clientAuth)); keyPurposeIds.add(KeyPurposeId.getInstance(KeyPurposeId.id_kp_emailProtection)); extensionList.add(new Extension(X509Extension.extendedKeyUsage, false, new ExtendedKeyUsage(keyPurposeIds.toArray(new KeyPurposeId[keyPurposeIds.size()])).getEncoded())); pkiMessages.setExtensions(extensionList.toArray(new Extension[extensionList.size()])); byte[] result = pkiMessages.createKeyUpdateMessageWithLocalKey(pki.getRACert(), keyPair); ASN1InputStream asn1InputStream = new ASN1InputStream(result); ASN1Primitive asn1Primitive = asn1InputStream.readObject(); PKIMessage pkiMessage = PKIMessage.getInstance(asn1Primitive); // Check the Body CertReqMsg[] certReqMsgs = CertReqMessages.getInstance(pkiMessage.getBody().getContent()) .toCertReqMsgArray(); // Extensions check // KeyUsage KeyUsage verifyKeyUsage = KeyUsage.getInstance(certReqMsgs[0].getCertReq().getCertTemplate().getExtensions() .getExtensionParsedValue(Extension.keyUsage)); Assert.assertEquals(KeyUsage.digitalSignature | KeyUsage.nonRepudiation, verifyKeyUsage.getBytes()[0] & 0xFF); // Extended KeyUsage ExtendedKeyUsage verifyExtendedKeyUsage = ExtendedKeyUsage .fromExtensions(certReqMsgs[0].getCertReq().getCertTemplate().getExtensions()); Assert.assertTrue(verifyExtendedKeyUsage.hasKeyPurposeId(KeyPurposeId.id_kp_clientAuth)); Assert.assertTrue(verifyExtendedKeyUsage.hasKeyPurposeId(KeyPurposeId.id_kp_emailProtection)); }
From source file:org.cryptoworkshop.ximix.node.crypto.key.BLSKeyManager.java
License:Apache License
private X509CertificateHolder createCertificate(String keyID, int sequenceNo, PrivateKey privKey) throws GeneralSecurityException, OperatorCreationException, IOException { String name = "C=AU, O=Ximix Network Node, OU=" + nodeContext.getName(); ///*from w ww .ja v a 2s . c om*/ // create the certificate - version 3 // X509v3CertificateBuilder v3CertBuilder = new X509v3CertificateBuilder(new X500Name(name), BigInteger.valueOf(1), new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30), new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365)), new X500Name(name), this.fetchPublicKey(keyID)); // we use keyUsage extension to distinguish between signing and encryption keys if (signingKeys.contains(keyID)) { v3CertBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature)); } else { v3CertBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.dataEncipherment)); } v3CertBuilder.addExtension(XimixObjectIdentifiers.ximixShareIdExtension, true, new ASN1Integer(sequenceNo)); return v3CertBuilder.build(new JcaContentSignerBuilder("SHA256withECDSA").setProvider("BC").build(privKey)); }
From source file:org.eclipse.milo.opcua.stack.core.util.SelfSignedCertificateGenerator.java
License:Open Source License
protected void addKeyUsage(X509v3CertificateBuilder certificateBuilder) throws CertIOException { certificateBuilder.addExtension(Extension.keyUsage, false, new KeyUsage(KeyUsage.dataEncipherment | KeyUsage.digitalSignature | KeyUsage.keyAgreement | KeyUsage.keyCertSign | KeyUsage.keyEncipherment | KeyUsage.nonRepudiation)); }
From source file:org.ejbca.core.ejb.authentication.web.WebAuthenticationProviderSessionBeanTest.java
License:Open Source License
private static X509Certificate generateUnbornCert(String dn, String policyId, PrivateKey privKey, PublicKey pubKey, String sigAlg, boolean isCA) throws NoSuchAlgorithmException, SignatureException, InvalidKeyException, IllegalStateException, NoSuchProviderException, OperatorCreationException, CertificateException, IOException { int keyusage = X509KeyUsage.keyCertSign + X509KeyUsage.cRLSign; // Create self signed certificate Date firstDate = new Date(); // Set starting date to tomorrow firstDate.setTime(firstDate.getTime() + (24 * 3600 * 1000)); Date lastDate = new Date(); // Set Expiry in two days lastDate.setTime(lastDate.getTime() + ((2 * 24 * 60 * 60 * 1000))); // Transform the PublicKey to be sure we have it in a format that the X509 certificate generator handles, it might be // a CVC public key that is passed as parameter PublicKey publicKey = null;//www .j a v a 2 s . c o m if (pubKey instanceof RSAPublicKey) { RSAPublicKey rsapk = (RSAPublicKey) pubKey; RSAPublicKeySpec rSAPublicKeySpec = new RSAPublicKeySpec(rsapk.getModulus(), rsapk.getPublicExponent()); try { publicKey = KeyFactory.getInstance("RSA").generatePublic(rSAPublicKeySpec); } catch (InvalidKeySpecException e) { publicKey = pubKey; } } else if (pubKey instanceof ECPublicKey) { ECPublicKey ecpk = (ECPublicKey) pubKey; try { ECPublicKeySpec ecspec = new ECPublicKeySpec(ecpk.getW(), ecpk.getParams()); // will throw NPE if key is "implicitlyCA" publicKey = KeyFactory.getInstance("EC").generatePublic(ecspec); } catch (InvalidKeySpecException e) { publicKey = pubKey; } catch (NullPointerException e) { publicKey = pubKey; } } else { publicKey = pubKey; } // Serialnumber is random bits, where random generator is initialized with Date.getTime() when this // bean is created. byte[] serno = new byte[8]; SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); random.setSeed(new Date().getTime()); random.nextBytes(serno); final SubjectPublicKeyInfo pkinfo = new SubjectPublicKeyInfo( (ASN1Sequence) ASN1Primitive.fromByteArray(publicKey.getEncoded())); X509v3CertificateBuilder certbuilder = new X509v3CertificateBuilder(CertTools.stringToBcX500Name(dn), new java.math.BigInteger(serno).abs(), firstDate, lastDate, CertTools.stringToBcX500Name(dn), pkinfo); // Basic constranits is always critical and MUST be present at-least in CA-certificates. BasicConstraints bc = new BasicConstraints(isCA); certbuilder.addExtension(Extension.basicConstraints, true, bc); // Put critical KeyUsage in CA-certificates if (isCA) { X509KeyUsage ku = new X509KeyUsage(keyusage); certbuilder.addExtension(Extension.keyUsage, true, ku); } // Subject and Authority key identifier is always non-critical and MUST be present for certificates to verify in Firefox. try { if (isCA) { ASN1InputStream spkiAsn1InputStream = new ASN1InputStream( new ByteArrayInputStream(publicKey.getEncoded())); ASN1InputStream apkiAsn1InputStream = new ASN1InputStream( new ByteArrayInputStream(publicKey.getEncoded())); try { SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo( (ASN1Sequence) spkiAsn1InputStream.readObject()); X509ExtensionUtils x509ExtensionUtils = new BcX509ExtensionUtils(); SubjectKeyIdentifier ski = x509ExtensionUtils.createSubjectKeyIdentifier(spki); SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo( (ASN1Sequence) apkiAsn1InputStream.readObject()); AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki); certbuilder.addExtension(Extension.subjectKeyIdentifier, false, ski); certbuilder.addExtension(Extension.authorityKeyIdentifier, false, aki); } finally { spkiAsn1InputStream.close(); apkiAsn1InputStream.close(); } } } catch (IOException e) { // do nothing } // CertificatePolicies extension if supplied policy ID, always non-critical if (policyId != null) { PolicyInformation pi = new PolicyInformation(new ASN1ObjectIdentifier(policyId)); DERSequence seq = new DERSequence(pi); certbuilder.addExtension(Extension.certificatePolicies, false, seq); } final ContentSigner signer = new BufferingContentSigner(new JcaContentSignerBuilder("SHA1withRSA") .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(privKey), 20480); final X509CertificateHolder certHolder = certbuilder.build(signer); final X509Certificate selfcert = (X509Certificate) CertTools.getCertfromByteArray(certHolder.getEncoded()); return selfcert; }