List of usage examples for org.bouncycastle.jce X509KeyUsage cRLSign
int cRLSign
To view the source code for org.bouncycastle.jce X509KeyUsage cRLSign.
Click Source Link
From source file:me.it_result.ca.bouncycastle.BouncyCABase.java
License:Open Source License
protected X509V3CertificateGenerator assembleCertificate(PublicKey publicKey, PublicKey caPublicKey, String subjectDN, String issuerDN, BigInteger serialNumber, boolean ca, int validityDays) throws CertificateParsingException, InvalidKeyException, CertificateEncodingException, IllegalStateException, NoSuchAlgorithmException, SignatureException, FileNotFoundException { certGen.setIssuerDN(new X509Principal(issuerDN)); certGen.setNotBefore(new Date()); Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(System.currentTimeMillis()); cal.add(Calendar.DAY_OF_MONTH, validityDays); certGen.setNotAfter(cal.getTime());// www . ja v a 2 s . c o m certGen.setPublicKey(publicKey); certGen.setSerialNumber(serialNumber); certGen.setSignatureAlgorithm(signatureAlgorithm); certGen.setSubjectDN(new X509Principal(subjectDN)); X509KeyUsage keyUsage; if (ca) keyUsage = new X509KeyUsage(X509KeyUsage.cRLSign | X509KeyUsage.keyCertSign); else keyUsage = new X509KeyUsage(X509KeyUsage.keyEncipherment | X509KeyUsage.digitalSignature); certGen.addExtension(X509Extensions.KeyUsage, true, keyUsage.getDEREncoded()); BasicConstraints basicConstraints = new BasicConstraints(ca); certGen.addExtension(X509Extensions.BasicConstraints, true, basicConstraints.getDEREncoded()); SubjectKeyIdentifierStructure subjectKeyId = new SubjectKeyIdentifierStructure(publicKey); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, subjectKeyId.getDEREncoded()); AuthorityKeyIdentifierStructure authorityKeyId = new AuthorityKeyIdentifierStructure(caPublicKey); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, authorityKeyId.getDEREncoded()); return certGen; }
From source file:me.it_result.ca.bouncycastle.BouncyCATest.java
License:Open Source License
private void verifyCertificate(X509Certificate cert, String subjectName, BigInteger serialNumber, boolean ca, boolean server, Date minBeforeDate, Date maxBeforeDate) throws Exception { X509Certificate caCert = this.ca.getCACertificate(); // See http://citrixblogger.org/2010/09/10/certificate-public-key-usage/ for a good assembly of key usage guideline materials int expectedKeyUsage; if (ca)//from ww w .j av a 2 s .c o m expectedKeyUsage = X509KeyUsage.cRLSign | X509KeyUsage.keyCertSign; else expectedKeyUsage = X509KeyUsage.digitalSignature | X509KeyUsage.keyEncipherment;// | X509KeyUsage.dataEncipherment; new X509Assertions(cert).type("X.509").version(3).issuedBy(caCert).subjectName(subjectName) .serialNumber(serialNumber).validDuring(VALIDITY_DAYS, minBeforeDate, maxBeforeDate) .caCertificate(ca).containsSKI().containsAKI() .eku(ca ? null : new KeyPurposeId[] { server ? KeyPurposeId.id_kp_serverAuth : KeyPurposeId.id_kp_clientAuth }) .keyUsage(expectedKeyUsage).noMoreExtensions().signatureAlgrithm(jdkSignatureAlgorithm); }
From source file:net.maritimecloud.identityregistry.utils.CertificateUtil.java
License:Apache License
/** * Builds and signs a certificate. The certificate will be build on the given subject-public-key and signed with * the given issuer-private-key. The issuer and subject will be identified in the strings provided. * * @return A signed X509Certificate//from ww w .ja v a2 s . c o m * @throws Exception */ public X509Certificate buildAndSignCert(BigInteger serialNumber, PrivateKey signerPrivateKey, PublicKey signerPublicKey, PublicKey subjectPublicKey, X500Name issuer, X500Name subject, Map<String, String> customAttrs, String type) throws Exception { // Dates are converted to GMT/UTC inside the cert builder Calendar cal = Calendar.getInstance(); Date now = cal.getTime(); Date expire = new GregorianCalendar(CERT_EXPIRE_YEAR, 0, 1).getTime(); X509v3CertificateBuilder certV3Bldr = new JcaX509v3CertificateBuilder(issuer, serialNumber, now, // Valid from now... expire, // until CERT_EXPIRE_YEAR subject, subjectPublicKey); JcaX509ExtensionUtils extensionUtil = new JcaX509ExtensionUtils(); // Create certificate extensions if ("ROOTCA".equals(type)) { certV3Bldr = certV3Bldr.addExtension(Extension.basicConstraints, true, new BasicConstraints(true)) .addExtension(Extension.keyUsage, true, new X509KeyUsage(X509KeyUsage.digitalSignature | X509KeyUsage.nonRepudiation | X509KeyUsage.keyEncipherment | X509KeyUsage.keyCertSign | X509KeyUsage.cRLSign)); } else if ("INTERMEDIATE".equals(type)) { certV3Bldr = certV3Bldr.addExtension(Extension.basicConstraints, true, new BasicConstraints(true)) .addExtension(Extension.keyUsage, true, new X509KeyUsage(X509KeyUsage.digitalSignature | X509KeyUsage.nonRepudiation | X509KeyUsage.keyEncipherment | X509KeyUsage.keyCertSign | X509KeyUsage.cRLSign)); } else { // Subject Alternative Name GeneralName[] genNames = null; if (customAttrs != null && !customAttrs.isEmpty()) { genNames = new GeneralName[customAttrs.size()]; Iterator<Map.Entry<String, String>> it = customAttrs.entrySet().iterator(); int idx = 0; while (it.hasNext()) { Map.Entry<String, String> pair = it.next(); //genNames[idx] = new GeneralName(GeneralName.otherName, new DERUTF8String(pair.getKey() + ";" + pair.getValue())); DERSequence othernameSequence = new DERSequence( new ASN1Encodable[] { new ASN1ObjectIdentifier(pair.getKey()), new DERTaggedObject(true, 0, new DERUTF8String(pair.getValue())) }); genNames[idx] = new GeneralName(GeneralName.otherName, othernameSequence); idx++; } } if (genNames != null) { certV3Bldr = certV3Bldr.addExtension(Extension.subjectAlternativeName, false, new GeneralNames(genNames)); } } // Basic extension setup certV3Bldr = certV3Bldr .addExtension(Extension.authorityKeyIdentifier, false, extensionUtil.createAuthorityKeyIdentifier(signerPublicKey)) .addExtension(Extension.subjectKeyIdentifier, false, extensionUtil.createSubjectKeyIdentifier(subjectPublicKey)); // CRL Distribution Points DistributionPointName distPointOne = new DistributionPointName( new GeneralNames(new GeneralName(GeneralName.uniformResourceIdentifier, CRL_URL))); DistributionPoint[] distPoints = new DistributionPoint[1]; distPoints[0] = new DistributionPoint(distPointOne, null, null); certV3Bldr.addExtension(Extension.cRLDistributionPoints, false, new CRLDistPoint(distPoints)); // OCSP endpoint GeneralName ocspName = new GeneralName(GeneralName.uniformResourceIdentifier, OCSP_URL); AuthorityInformationAccess authorityInformationAccess = new AuthorityInformationAccess( X509ObjectIdentifiers.ocspAccessMethod, ocspName); certV3Bldr.addExtension(Extension.authorityInfoAccess, false, authorityInformationAccess); // Create the key signer JcaContentSignerBuilder builder = new JcaContentSignerBuilder(SIGNER_ALGORITHM); builder.setProvider(BC_PROVIDER_NAME); ContentSigner signer = builder.build(signerPrivateKey); return new JcaX509CertificateConverter().setProvider(BC_PROVIDER_NAME) .getCertificate(certV3Bldr.build(signer)); }
From source file:net.maritimecloud.pki.CertificateBuilder.java
License:Apache License
/** * Builds and signs a certificate. The certificate will be build on the given subject-public-key and signed with * the given issuer-private-key. The issuer and subject will be identified in the strings provided. * * @param serialNumber The serialnumber of the new certificate. * @param signerPrivateKey Private key for signing the certificate * @param signerPublicKey Public key of the signing certificate * @param subjectPublicKey Public key for the new certificate * @param issuer DN of the signing certificate * @param subject DN of the new certificate * @param customAttrs The custom MC attributes to include in the certificate * @param type Type of certificate, can be "ROOT", "INTERMEDIATE" or "ENTITY". * @param ocspUrl OCSP endpoint/* w w w .ja v a 2 s . c o m*/ * @param crlUrl CRL endpoint - can be null * @return A signed X509Certificate * @throws Exception Throws exception on certificate generation errors. */ public X509Certificate buildAndSignCert(BigInteger serialNumber, PrivateKey signerPrivateKey, PublicKey signerPublicKey, PublicKey subjectPublicKey, X500Name issuer, X500Name subject, Map<String, String> customAttrs, String type, String ocspUrl, String crlUrl) throws Exception { // Dates are converted to GMT/UTC inside the cert builder Calendar cal = Calendar.getInstance(); Date now = cal.getTime(); Date expire = new GregorianCalendar(CERT_EXPIRE_YEAR, 0, 1).getTime(); X509v3CertificateBuilder certV3Bldr = new JcaX509v3CertificateBuilder(issuer, serialNumber, now, // Valid from now... expire, // until CERT_EXPIRE_YEAR subject, subjectPublicKey); JcaX509ExtensionUtils extensionUtil = new JcaX509ExtensionUtils(); // Create certificate extensions if ("ROOTCA".equals(type)) { certV3Bldr = certV3Bldr.addExtension(Extension.basicConstraints, true, new BasicConstraints(true)) .addExtension(Extension.keyUsage, true, new X509KeyUsage(X509KeyUsage.digitalSignature | X509KeyUsage.nonRepudiation | X509KeyUsage.keyEncipherment | X509KeyUsage.keyCertSign | X509KeyUsage.cRLSign)); } else if ("INTERMEDIATE".equals(type)) { certV3Bldr = certV3Bldr.addExtension(Extension.basicConstraints, true, new BasicConstraints(true)) .addExtension(Extension.keyUsage, true, new X509KeyUsage(X509KeyUsage.digitalSignature | X509KeyUsage.nonRepudiation | X509KeyUsage.keyEncipherment | X509KeyUsage.keyCertSign | X509KeyUsage.cRLSign)); } else { // Subject Alternative Name GeneralName[] genNames = null; if (customAttrs != null && !customAttrs.isEmpty()) { genNames = new GeneralName[customAttrs.size()]; Iterator<Map.Entry<String, String>> it = customAttrs.entrySet().iterator(); int idx = 0; while (it.hasNext()) { Map.Entry<String, String> pair = it.next(); if (PKIConstants.X509_SAN_DNSNAME.equals(pair.getKey())) { genNames[idx] = new GeneralName(GeneralName.dNSName, pair.getValue()); } else { //genNames[idx] = new GeneralName(GeneralName.otherName, new DERUTF8String(pair.getKey() + ";" + pair.getValue())); DERSequence othernameSequence = new DERSequence( new ASN1Encodable[] { new ASN1ObjectIdentifier(pair.getKey()), new DERTaggedObject(true, 0, new DERUTF8String(pair.getValue())) }); genNames[idx] = new GeneralName(GeneralName.otherName, othernameSequence); } idx++; } } if (genNames != null) { certV3Bldr = certV3Bldr.addExtension(Extension.subjectAlternativeName, false, new GeneralNames(genNames)); } } // Basic extension setup certV3Bldr = certV3Bldr .addExtension(Extension.authorityKeyIdentifier, false, extensionUtil.createAuthorityKeyIdentifier(signerPublicKey)) .addExtension(Extension.subjectKeyIdentifier, false, extensionUtil.createSubjectKeyIdentifier(subjectPublicKey)); // CRL Distribution Points DistributionPointName distPointOne = new DistributionPointName( new GeneralNames(new GeneralName(GeneralName.uniformResourceIdentifier, crlUrl))); DistributionPoint[] distPoints = new DistributionPoint[1]; distPoints[0] = new DistributionPoint(distPointOne, null, null); certV3Bldr.addExtension(Extension.cRLDistributionPoints, false, new CRLDistPoint(distPoints)); // OCSP endpoint - is not available for the CAs if (ocspUrl != null) { GeneralName ocspName = new GeneralName(GeneralName.uniformResourceIdentifier, ocspUrl); AuthorityInformationAccess authorityInformationAccess = new AuthorityInformationAccess( X509ObjectIdentifiers.ocspAccessMethod, ocspName); certV3Bldr.addExtension(Extension.authorityInfoAccess, false, authorityInformationAccess); } // Create the key signer JcaContentSignerBuilder builder = new JcaContentSignerBuilder(SIGNER_ALGORITHM); builder.setProvider(BC_PROVIDER_NAME); ContentSigner signer = builder.build(signerPrivateKey); return new JcaX509CertificateConverter().setProvider(BC_PROVIDER_NAME) .getCertificate(certV3Bldr.build(signer)); }
From source file:net.solarnetwork.node.setup.test.PKITestUtils.java
License:Open Source License
public static X509Certificate generateNewCACert(PublicKey publicKey, String subject, X509Certificate issuer, PrivateKey issuerKey, String caDN) throws Exception { final X500Name issuerDn = (issuer == null ? new X500Name(subject) : JcaX500NameUtil.getSubject(issuer)); final X500Name subjectDn = new X500Name(subject); final BigInteger serial = getNextSerialNumber(); final Date notBefore = new Date(); final Date notAfter = new Date(System.currentTimeMillis() + 1000L * 60L * 60L); JcaX509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuerDn, serial, notBefore, notAfter, subjectDn, publicKey);//from w w w . ja v a 2s . c om // add "CA" extension BasicConstraints basicConstraints; if (issuer == null) { basicConstraints = new BasicConstraints(true); } else { int issuerPathLength = issuer.getBasicConstraints(); basicConstraints = new BasicConstraints(issuerPathLength - 1); } builder.addExtension(X509Extension.basicConstraints, true, basicConstraints); // add subjectKeyIdentifier JcaX509ExtensionUtils utils = new JcaX509ExtensionUtils(); SubjectKeyIdentifier ski = utils.createSubjectKeyIdentifier(publicKey); builder.addExtension(X509Extension.subjectKeyIdentifier, false, ski); // add authorityKeyIdentifier GeneralNames issuerName = new GeneralNames(new GeneralName(GeneralName.directoryName, caDN)); AuthorityKeyIdentifier aki = utils.createAuthorityKeyIdentifier(publicKey); aki = new AuthorityKeyIdentifier(aki.getKeyIdentifier(), issuerName, serial); builder.addExtension(X509Extension.authorityKeyIdentifier, false, aki); // add keyUsage X509KeyUsage keyUsage = new X509KeyUsage(X509KeyUsage.cRLSign | X509KeyUsage.digitalSignature | X509KeyUsage.keyCertSign | X509KeyUsage.nonRepudiation); builder.addExtension(X509Extension.keyUsage, true, keyUsage); JcaContentSignerBuilder signerBuilder = new JcaContentSignerBuilder("SHA256WithRSA"); ContentSigner signer = signerBuilder.build(issuerKey); X509CertificateHolder holder = builder.build(signer); JcaX509CertificateConverter converter = new JcaX509CertificateConverter(); return converter.getCertificate(holder); }
From source file:org.cesecore.certificates.ca.internal.CertificateValidityTest.java
License:Open Source License
private void testBaseTestCertificateValidity(long encodedValidity) throws Exception { KeyPair keys = KeyTools.genKeys("1024", "RSA"); X509Certificate cacert = CertTools.genSelfCertForPurpose("CN=dummy2", 100, null, keys.getPrivate(), keys.getPublic(), AlgorithmConstants.SIGALG_SHA1_WITH_RSA, true, X509KeyUsage.cRLSign | X509KeyUsage.keyCertSign, true); EndEntityInformation subject = new EndEntityInformation(); final CertificateProfile cp = new CertificateProfile(CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER); cp.setValidity(encodedValidity);//from w w w . ja v a2 s .co m cp.setAllowValidityOverride(false); // First see that when we don't have a specified time requested and validity override is not allowed, the end time should be ruled by the certificate profile. CertificateValidity cv = new CertificateValidity(subject, cp, null, null, cacert, false); Date notBefore = cv.getNotBefore(); Date notAfter = cv.getNotAfter(); Date now = new Date(); Calendar cal1 = Calendar.getInstance(); cal1.add(Calendar.DAY_OF_MONTH, 49); Calendar cal2 = Calendar.getInstance(); cal2.add(Calendar.DAY_OF_MONTH, 51); assertTrue(notBefore.before(now)); assertTrue(notAfter.after(cal1.getTime())); assertTrue(notAfter.before(cal2.getTime())); // See that a requested validity does not affect it Calendar requestNotBefore = Calendar.getInstance(); requestNotBefore.add(Calendar.DAY_OF_MONTH, 2); Calendar requestNotAfter = Calendar.getInstance(); requestNotAfter.add(Calendar.DAY_OF_MONTH, 25); cv = new CertificateValidity(subject, cp, requestNotBefore.getTime(), requestNotAfter.getTime(), cacert, false); notBefore = cv.getNotBefore(); notAfter = cv.getNotAfter(); assertTrue(notBefore.before(now)); assertTrue(notAfter.after(cal1.getTime())); assertTrue(notAfter.before(cal2.getTime())); // Add extended information for the user and see that it does not affect it either ExtendedInformation ei = new ExtendedInformation(); ei.setCustomData(ExtendedInformation.CUSTOM_STARTTIME, "10:0:0"); // days:hours:minutes ei.setCustomData(ExtendedInformation.CUSTOM_ENDTIME, "30:0:0"); subject.setExtendedinformation(ei); cv = new CertificateValidity(subject, cp, requestNotBefore.getTime(), requestNotAfter.getTime(), cacert, false); notBefore = cv.getNotBefore(); notAfter = cv.getNotAfter(); assertTrue(notBefore.before(now)); assertTrue(notAfter.after(cal1.getTime())); assertTrue(notAfter.before(cal2.getTime())); // Now allow validity override cp.setAllowValidityOverride(true); // Now we should get what's in the EndEntityInformation extended information cv = new CertificateValidity(subject, cp, requestNotBefore.getTime(), requestNotAfter.getTime(), cacert, false); notBefore = cv.getNotBefore(); notAfter = cv.getNotAfter(); cal1 = Calendar.getInstance(); cal1.add(Calendar.DAY_OF_MONTH, 9); cal2 = Calendar.getInstance(); cal2.add(Calendar.DAY_OF_MONTH, 11); assertTrue(notBefore.after(cal1.getTime())); assertTrue(notBefore.before(cal2.getTime())); cal1 = Calendar.getInstance(); cal1.add(Calendar.DAY_OF_MONTH, 29); cal2 = Calendar.getInstance(); cal2.add(Calendar.DAY_OF_MONTH, 31); assertTrue(notAfter.after(cal1.getTime())); assertTrue(notAfter.before(cal2.getTime())); // Remove extended information from EndEntityInformation and we should get what we pass as parameters to CertificateValidity subject.setExtendedinformation(null); cv = new CertificateValidity(subject, cp, requestNotBefore.getTime(), requestNotAfter.getTime(), cacert, false); notBefore = cv.getNotBefore(); notAfter = cv.getNotAfter(); cal1 = Calendar.getInstance(); cal1.add(Calendar.DAY_OF_MONTH, 1); cal2 = Calendar.getInstance(); cal2.add(Calendar.DAY_OF_MONTH, 3); assertTrue(notBefore.after(cal1.getTime())); assertTrue(notBefore.before(cal2.getTime())); cal1 = Calendar.getInstance(); cal1.add(Calendar.DAY_OF_MONTH, 23); cal2 = Calendar.getInstance(); cal2.add(Calendar.DAY_OF_MONTH, 26); assertTrue(notAfter.after(cal1.getTime())); assertTrue(notAfter.before(cal2.getTime())); // Check that we can not supersede the certificate profile end time requestNotAfter = Calendar.getInstance(); requestNotAfter.add(Calendar.DAY_OF_MONTH, 200); cv = new CertificateValidity(subject, cp, requestNotBefore.getTime(), requestNotAfter.getTime(), cacert, false); notBefore = cv.getNotBefore(); notAfter = cv.getNotAfter(); cal1 = Calendar.getInstance(); cal2 = Calendar.getInstance(); // This will be counted in number of days since notBefore, and notBefore here is taken from requestNotBefore which is two, // so we have to add 2 to certificate profile validity to get the resulting notAfter but not if certificate end is an // absolute end date. if (encodedValidity > Integer.MAX_VALUE) { cal1.add(Calendar.DAY_OF_MONTH, 49); cal2.add(Calendar.DAY_OF_MONTH, 51); } else { cal1.add(Calendar.DAY_OF_MONTH, 51); cal2.add(Calendar.DAY_OF_MONTH, 53); } assertTrue(notAfter.after(cal1.getTime())); assertTrue(notAfter.before(cal2.getTime())); // Check that we can not supersede the CA end time cp.setValidity(400); cv = new CertificateValidity(subject, cp, requestNotBefore.getTime(), requestNotAfter.getTime(), cacert, false); notBefore = cv.getNotBefore(); notAfter = cv.getNotAfter(); // This will be the CA certificate's notAfter cal1 = Calendar.getInstance(); cal1.add(Calendar.DAY_OF_MONTH, 99); cal2 = Calendar.getInstance(); cal2.add(Calendar.DAY_OF_MONTH, 101); assertTrue(notAfter.after(cal1.getTime())); assertTrue(notAfter.before(cal2.getTime())); // Unless it is a root CA, then we should be able to get a new validity after, to be able to update CA certificate cv = new CertificateValidity(subject, cp, requestNotBefore.getTime(), requestNotAfter.getTime(), cacert, true); notBefore = cv.getNotBefore(); notAfter = cv.getNotAfter(); cal1 = Calendar.getInstance(); cal1.add(Calendar.DAY_OF_MONTH, 199); cal2 = Calendar.getInstance(); cal2.add(Calendar.DAY_OF_MONTH, 201); assertTrue(notAfter.after(cal1.getTime())); assertTrue(notAfter.before(cal2.getTime())); // Check that we can request a validity time before "now" using requested notBefore (in the CSR) requestNotBefore = Calendar.getInstance(); requestNotBefore.add(Calendar.DAY_OF_MONTH, -10); cv = new CertificateValidity(subject, cp, requestNotBefore.getTime(), requestNotAfter.getTime(), cacert, false); notBefore = cv.getNotBefore(); notAfter = cv.getNotAfter(); cal1 = Calendar.getInstance(); cal1.add(Calendar.DAY_OF_MONTH, -9); cal2 = Calendar.getInstance(); cal2.add(Calendar.DAY_OF_MONTH, -11); assertTrue(notBefore.before(cal1.getTime())); assertTrue(notBefore.after(cal2.getTime())); // This will be the CA certificate's notAfter cal1 = Calendar.getInstance(); cal1.add(Calendar.DAY_OF_MONTH, 99); cal2 = Calendar.getInstance(); cal2.add(Calendar.DAY_OF_MONTH, 101); assertTrue(notAfter.after(cal1.getTime())); assertTrue(notAfter.before(cal2.getTime())); // Check that we can request a validity time before "now" using ExtendedInformation as well (set to 10 days before) ei = new ExtendedInformation(); cal1 = Calendar.getInstance(); cal1.add(Calendar.DAY_OF_MONTH, -10); ei.setCustomData(ExtendedInformation.CUSTOM_STARTTIME, ValidityDate.formatAsUTC(cal1.getTime())); ei.setCustomData(ExtendedInformation.CUSTOM_ENDTIME, "200:0:0"); subject.setExtendedinformation(ei); cv = new CertificateValidity(subject, cp, null, null, cacert, false); notBefore = cv.getNotBefore(); notAfter = cv.getNotAfter(); cal1 = Calendar.getInstance(); cal1.add(Calendar.DAY_OF_MONTH, -9); cal2 = Calendar.getInstance(); cal2.add(Calendar.DAY_OF_MONTH, -11); assertTrue(notBefore.before(cal1.getTime())); assertTrue(notBefore.after(cal2.getTime())); // This will be the CA certificate's notAfter cal1 = Calendar.getInstance(); cal1.add(Calendar.DAY_OF_MONTH, 99); cal2 = Calendar.getInstance(); cal2.add(Calendar.DAY_OF_MONTH, 101); assertTrue(notAfter.after(cal1.getTime())); assertTrue(notAfter.before(cal2.getTime())); // See that it is not allowed when allowValidityOverride is set to false cp.setAllowValidityOverride(false); cv = new CertificateValidity(subject, cp, null, null, cacert, false); notBefore = cv.getNotBefore(); notAfter = cv.getNotAfter(); cal1 = Calendar.getInstance(); cal1.add(Calendar.DAY_OF_MONTH, 1); cal2 = Calendar.getInstance(); cal2.add(Calendar.DAY_OF_MONTH, -1); assertTrue(notBefore.before(cal1.getTime())); assertTrue(notBefore.after(cal2.getTime())); subject.setExtendedinformation(null); // Reset after test cp.setAllowValidityOverride(true); // Check that ca.toolateexpiredate setting in ejbca.properties is in effect Calendar cal = Calendar.getInstance(); cal.add(Calendar.DAY_OF_MONTH, 5); CertificateValidity.setTooLateExpireDate(cal.getTime()); boolean thrown = false; try { cv = new CertificateValidity(subject, cp, requestNotBefore.getTime(), requestNotAfter.getTime(), cacert, false); } catch (IllegalValidityException e) { thrown = true; //log.debug(e.getMessage()); String msg = e.getMessage(); // When running from within eclipse it will not have the correct internalresources. if (!msg.contains("Requested expire date is not before the configured 'ca.toolateexpiredate'") && (!msg.equals("signsession.errorbeyondtoolateexpiredate"))) { assertTrue(msg, false); } } assertTrue(thrown); CertificateValidity.setTooLateExpireDate(new Date(Long.MAX_VALUE)); }
From source file:org.cesecore.certificates.ca.X509CATest.java
License:Open Source License
private static X509CA createTestCA(CryptoToken cryptoToken, final String cadn, final String sigAlg, Date notBefore, Date notAfter) throws Exception { cryptoToken.generateKeyPair(getTestKeySpec(sigAlg), CAToken.SOFTPRIVATESIGNKEYALIAS); cryptoToken.generateKeyPair(getTestKeySpec(sigAlg), CAToken.SOFTPRIVATEDECKEYALIAS); // Create CAToken Properties caTokenProperties = new Properties(); caTokenProperties.setProperty(CATokenConstants.CAKEYPURPOSE_CERTSIGN_STRING, CAToken.SOFTPRIVATESIGNKEYALIAS); caTokenProperties.setProperty(CATokenConstants.CAKEYPURPOSE_CRLSIGN_STRING, CAToken.SOFTPRIVATESIGNKEYALIAS); caTokenProperties.setProperty(CATokenConstants.CAKEYPURPOSE_DEFAULT_STRING, CAToken.SOFTPRIVATEDECKEYALIAS); CAToken caToken = new CAToken(cryptoToken.getId(), caTokenProperties); // Set key sequence so that next sequence will be 00001 (this is the default though so not really needed here) caToken.setKeySequence(CAToken.DEFAULT_KEYSEQUENCE); caToken.setKeySequenceFormat(StringTools.KEY_SEQUENCE_FORMAT_NUMERIC); caToken.setSignatureAlgorithm(sigAlg); caToken.setEncryptionAlgorithm(AlgorithmConstants.SIGALG_SHA256_WITH_RSA); // No extended services X509CAInfo cainfo = new X509CAInfo(cadn, "TEST", CAConstants.CA_ACTIVE, CertificateProfileConstants.CERTPROFILE_FIXED_ROOTCA, 3650, CAInfo.SELFSIGNED, null, caToken); cainfo.setDescription("JUnit RSA CA"); X509CA x509ca = new X509CA(cainfo); x509ca.setCAToken(caToken);/*w ww . j av a 2 s .c o m*/ // A CA certificate final PublicKey publicKey = cryptoToken .getPublicKey(caToken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN)); final PrivateKey privateKey = cryptoToken .getPrivateKey(caToken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN)); int keyusage = X509KeyUsage.keyCertSign + X509KeyUsage.cRLSign; X509Certificate cacert = CertTools.genSelfCertForPurpose(cadn, 10L, "1.1.1.1", privateKey, publicKey, "SHA256WithRSA", true, keyusage, notBefore, notAfter, "BC"); assertNotNull(cacert); Collection<Certificate> cachain = new ArrayList<Certificate>(); cachain.add(cacert); x509ca.setCertificateChain(cachain); // Now our CA should be operational return x509ca; }
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. *//*from w w w .j a va 2s . c o 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.junit.util.PKCS11TestRunner.java
License:Open Source License
public X509CA createX509Ca() throws Exception { X509CA x509ca = CaTestUtils.createTestX509CAOptionalGenKeys(SUBJECT_DN, SystemTestsConfiguration.getPkcs11SlotPin(DEFAULT_TOKEN_PIN), false, true, "1024", X509KeyUsage.digitalSignature + X509KeyUsage.keyCertSign + X509KeyUsage.cRLSign); CAToken caToken = x509ca.getCAToken(); caToken.setProperty(CATokenConstants.CAKEYPURPOSE_CERTSIGN_STRING, ALIAS); caToken.setProperty(CATokenConstants.CAKEYPURPOSE_CRLSIGN_STRING, ALIAS); x509ca.setCAToken(caToken);//ww w.j a v a 2 s . co m caSession.addCA(alwaysAllowToken, x509ca); int cryptoTokenId = caToken.getCryptoTokenId(); cryptoTokenManagementSession.createKeyPair(alwaysAllowToken, cryptoTokenId, ALIAS, "1024"); CAInfo info = caSession.getCAInfo(alwaysAllowToken, x509ca.getCAId()); // We need the CA public key, since we activated the newly generated key, we know that it has a key purpose now PublicKey pk = cryptoTokenManagementSession.getPublicKey(alwaysAllowToken, cryptoTokenId, ALIAS) .getPublicKey(); EndEntityInformation user = new EndEntityInformation(super.getName(), info.getSubjectDN(), x509ca.getCAId(), null, null, new EndEntityType(EndEntityTypes.ENDUSER), 0, CertificateProfileConstants.CERTPROFILE_FIXED_ROOTCA, EndEntityConstants.TOKEN_USERGEN, 0, null); user.setStatus(EndEntityConstants.STATUS_NEW); user.setPassword("foo123"); SimpleRequestMessage req = new SimpleRequestMessage(pk, user.getUsername(), user.getPassword()); CertificateResponseMessage response = certificateCreateSession.createCertificate(alwaysAllowToken, user, req, org.cesecore.certificates.certificate.request.X509ResponseMessage.class, signSession.fetchCertGenParams()); Collection<Certificate> certs = info.getCertificateChain(); certs.add(response.getCertificate()); info.setCertificateChain(certs); caSession.editCA(alwaysAllowToken, info); casToRemove.put(x509ca.getCAId(), x509ca); return x509ca; }
From source file:org.cesecore.keybind.impl.OcspKeyBindingTest.java
License:Open Source License
@Test public void testOcspSigningCertificateValidationPositives() throws IOException, InvalidAlgorithmParameterException, InvalidKeyException, NoSuchAlgorithmException, SignatureException, IllegalStateException, NoSuchProviderException, OperatorCreationException, CertificateException { assertTrue(//from w w w . ja va 2 s . c o m "KU=digitalSignature and EKU=id_kp_OCSPSigning should be treated as a valid OCSP singing certificate.", OcspKeyBinding .isOcspSigningCertificate(getCertificate(X509KeyUsage.digitalSignature, ekuExtensionOnly))); assertTrue( "KU=digitalSignature and EKU=id_kp_OCSPSigning should be treated as a valid OCSP singing certificate.", OcspKeyBinding.isOcspSigningCertificate( getCertificate(X509KeyUsage.digitalSignature + X509KeyUsage.cRLSign, ekuExtensionOnly))); assertTrue( "KU=nonRepudiation and EKU=id_kp_OCSPSigning should be treated as a valid OCSP singing certificate.", OcspKeyBinding.isOcspSigningCertificate( getCertificate(X509KeyUsage.nonRepudiation + X509KeyUsage.cRLSign, ekuExtensionOnly))); assertTrue( "KU=digitalSignature+nonRepudiation and EKU=id_kp_OCSPSigning should be treated as a valid OCSP singing certificate.", OcspKeyBinding.isOcspSigningCertificate(getCertificate( X509KeyUsage.digitalSignature + X509KeyUsage.nonRepudiation, ekuExtensionOnly))); }