/** * return the issuer of the given cert as an X509PrincipalObject. */ public static X509Principal getIssuerX509Principal( X509Certificate cert) throws CertificateEncodingException { try { TBSCertificateStructure tbsCert = TBSCertificateStructure.getInstance( ASN1Primitive.fromByteArray(cert.getTBSCertificate())); return new X509Principal(X509Name.getInstance(tbsCert.getIssuer())); } catch (IOException e) { throw new CertificateEncodingException(e.toString()); } }
/** * return the subject of the given cert as an X509PrincipalObject. */ public static X509Principal getSubjectX509Principal( X509Certificate cert) throws CertificateEncodingException { try { TBSCertificateStructure tbsCert = TBSCertificateStructure.getInstance( ASN1Primitive.fromByteArray(cert.getTBSCertificate())); return new X509Principal(X509Name.getInstance(tbsCert.getSubject())); } catch (IOException e) { throw new CertificateEncodingException(e.toString()); } }
/** * return the issuer of the given CRL as an X509PrincipalObject. */ public static X509Principal getIssuerX509Principal( X509CRL crl) throws CRLException { try { TBSCertList tbsCertList = TBSCertList.getInstance( ASN1Primitive.fromByteArray(crl.getTBSCertList())); return new X509Principal(X509Name.getInstance(tbsCertList.getIssuer())); } catch (IOException e) { throw new CRLException(e.toString()); } }
public CertificationRequestInfo( ASN1Sequence seq) { version = (DERInteger)seq.getObjectAt(0); subject = X509Name.getInstance(seq.getObjectAt(1)); subjectPKInfo = SubjectPublicKeyInfo.getInstance(seq.getObjectAt(2)); // // some CertificationRequestInfo objects seem to treat this field // as optional. // if (seq.size() > 3) { DERTaggedObject tagobj = (DERTaggedObject)seq.getObjectAt(3); attributes = ASN1Set.getInstance(tagobj, false); } if ((subject == null) || (version == null) || (subjectPKInfo == null)) { throw new IllegalArgumentException("Not all mandatory fields set in CertificationRequestInfo generator."); } }
private void equalityTest(X509Name x509Name, X509Name x509Name1) { if (!x509Name.equals(x509Name1)) { fail("equality test failed for " + x509Name + " : " + x509Name1); } if (x509Name.hashCode() != x509Name1.hashCode()) { fail("hashCodeTest test failed for " + x509Name + " : " + x509Name1); } if (!x509Name.equals(x509Name1, true)) { fail("equality test failed for " + x509Name + " : " + x509Name1); } }
private void addEntry(final String alias) throws GeneralSecurityException { final KeyPair pair = KG.generateKeyPair(); // build a certificate generator final X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); final X500Principal dnName = new X500Principal("cn=" + alias); certGen.setSerialNumber(new BigInteger(256, RND)); certGen.setSubjectDN(new X509Name("dc=" + alias)); certGen.setIssuerDN(dnName); // use the same certGen.setNotBefore(new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000)); certGen.setNotAfter(new Date(System.currentTimeMillis() + 2 * 365 * 24 * 60 * 60 * 1000)); certGen.setPublicKey(pair.getPublic()); certGen.setSignatureAlgorithm("SHA256WithRSA"); final X509Certificate cert = certGen.generate(pair.getPrivate(), "BC"); ks.setEntry(alias, new KeyStore.PrivateKeyEntry(pair.getPrivate(), new X509Certificate[] { cert }), PP); }
private void addPublicEntry(final String alias) throws GeneralSecurityException { final KeyPair pair = KG.generateKeyPair(); // build a certificate generator final X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); final X500Principal dnName = new X500Principal("cn=" + alias); certGen.setSerialNumber(new BigInteger(256, RND)); certGen.setSubjectDN(new X509Name("dc=" + alias)); certGen.setIssuerDN(dnName); // use the same certGen.setNotBefore(new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000)); certGen.setNotAfter(new Date(System.currentTimeMillis() + 2 * 365 * 24 * 60 * 60 * 1000)); certGen.setPublicKey(pair.getPublic()); certGen.setSignatureAlgorithm("SHA256WithRSA"); final X509Certificate cert = certGen.generate(pair.getPrivate(), "BC"); ks.setEntry(alias, new KeyStore.TrustedCertificateEntry(cert), null); }
private static X509Name makePTLSX509Name(String subject) throws Exception { Vector tdn = new Vector(); Vector elems = new Vector(); StringTokenizer st = new StringTokenizer(subject,","); for (; st.hasMoreTokens() ;) { String s = st.nextToken(); // [key=value] if ( s.indexOf("=") == -1 ) throw new Exception("Invalid subject format: " + subject + " Offending value: " + s); String key = s.substring(0, s.indexOf("=")).trim(); String val = s.substring(s.indexOf("=") + 1).trim(); if ( val == null || val.equals("")) throw new Exception("Invalid subject format: " + subject + " Offending value: " + s); //logger.debug(key + "=" + val); String[] temp = {key, val}; tdn.addElement(temp); } // COM.claymoresystems.cert (puretls.jar) return CertRequest.makeSimpleDN(tdn); }
/** * Returns the <code>AuthorityKeyIdentifier</code> corresponding * to a given <code>PublicKey</code> * @param publicKey the given public key * @param issuer the certificate issuer * @param serial the certificate serial number * @return the authority key identifier of the public key * @throws IOException */ private AuthorityKeyIdentifier getAuthorityKeyIdentifier(PublicKey publicKey, String issuer, BigInteger serial) throws IOException { InputStream input; SubjectPublicKeyInfo keyInfo; ASN1EncodableVector vector; input = new ByteArrayInputStream(publicKey.getEncoded()); keyInfo = new SubjectPublicKeyInfo((ASN1Sequence)new ASN1InputStream(input).readObject()); vector = new ASN1EncodableVector(); vector.add(new GeneralName(new X509Name(issuer))); return new AuthorityKeyIdentifier(keyInfo, new GeneralNames(new DERSequence(vector)), serial); }
/** * Get String represetation of ResponderID * @param basResp * @return stringified responder ID */ private String responderIDtoString(BasicOCSPResp basResp) { if(basResp != null) { ResponderID respid = basResp.getResponseData().getResponderId().toASN1Object(); Object o = ((DERTaggedObject)respid.toASN1Object()).getObject(); if(o instanceof org.bouncycastle.asn1.DEROctetString) { org.bouncycastle.asn1.DEROctetString oc = (org.bouncycastle.asn1.DEROctetString)o; return "byKey: " + SignedDoc.bin2hex(oc.getOctets()); } else { X509Name name = new X509Name((ASN1Sequence)o); return "byName: " + name.toString(); } } else return null; }
private void createAndStoreCA(CertificateAuthority ca) throws Exception { KeyPair rootPair = KeyUtil.generateRSAKeyPair1024(ca.getCACredentialsProvider()); assertNotNull(rootPair); String rootSub = SUBJECT_PREFIX + "Temp Certificate Authority"; X509Name rootSubject = new X509Name(rootSub); GregorianCalendar cal = new GregorianCalendar(); Date start = cal.getTime(); cal.add(Calendar.YEAR, 1); Date end = cal.getTime(); X509Certificate root = CertUtil.generateCACertificate(ca.getCACredentialsProvider(), rootSubject, start, end, rootPair, CertUtil.SHA2_SIGNATURE_ALGORITHM); assertNotNull(root); ca.setCACredentials(root, rootPair.getPrivate(), null); X509Certificate r = ca.getCACertificate(); assertNotNull(r); assertEquals(r, root); }
public synchronized X509Certificate renewCertifcateAuthorityCredentials(Date expirationDate) throws CertificateAuthorityFault, NoCACredentialsFault { init(); try { X509Certificate oldcert = getCACertificate(false); int size = ((RSAPublicKey) oldcert.getPublicKey()).getModulus().bitLength(); KeyPair pair = KeyUtil.generateRSAKeyPair(getCACredentialsProvider(), size); X509Certificate cacert = CertUtil.generateCACertificate(getCACredentialsProvider(), new X509Name(oldcert .getSubjectDN().getName()), new Date(), expirationDate, pair, getSignatureAlgorithm()); deleteCACredentials(); this.setCACredentials(cacert, pair.getPrivate(), properties.getCertificateAuthorityPassword()); return cacert; } catch (Exception e) { logError(e.getMessage(), e); CertificateAuthorityFault fault = new CertificateAuthorityFault(); fault.setFaultString("Unexpected Error, could renew the CA credentials."); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (CertificateAuthorityFault) helper.getFault(); throw fault; } }
public static X509Certificate generateCACertificate(String provider, X509Name subject, Date start, Date expired, KeyPair pair, int numberOfCAs, String signatureAlgorthm) throws CertificateEncodingException, IllegalStateException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException, InvalidKeyException, IOException { // generate the certificate X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setIssuerDN(subject); certGen.setNotBefore(start); certGen.setNotAfter(expired); certGen.setSubjectDN(subject); certGen.setPublicKey(pair.getPublic()); certGen.setSignatureAlgorithm(signatureAlgorthm); certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(numberOfCAs)); certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign)); SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo((ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(pair.getPublic().getEncoded())).readObject()); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifier(spki)); SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo((ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(pair.getPublic().getEncoded())).readObject()); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifier(apki)); return certGen.generate(pair.getPrivate(), provider); }
private X509Certificate createAndStoreCAShort(CertificateAuthority ca, int seconds) throws Exception { KeyPair rootPair = KeyUtil.generateRSAKeyPair2048(ca.getCACredentialsProvider()); assertNotNull(rootPair); String rootSub = SUBJECT_PREFIX + "Temp Certificate Authority"; X509Name rootSubject = new X509Name(rootSub); GregorianCalendar cal = new GregorianCalendar(); Date start = cal.getTime(); cal.add(Calendar.SECOND, (seconds / 1000)); Date end = cal.getTime(); X509Certificate root = CertUtil.generateCACertificate(ca.getCACredentialsProvider(), rootSubject, start, end, rootPair, ca.getSignatureAlgorithm()); assertNotNull(root); ca.setCACredentials(root, rootPair.getPrivate(), null); X509Certificate r = ca.getCACertificate(); assertNotNull(r); if (!r.equals(root)) { throw new Exception("The CA certificate obtained was not expected"); } return r; }
private static String getComponent() { String component = null; while (true) { component = Util.getInput("Enter name component: "); if (component == null || component.trim().length() == 0) { return null; } component = component.trim(); if (X509Name.DefaultLookUp.get(component.toLowerCase()) == null) { System.out.println("Invalid component name"); } else { break; } } component = component.toUpperCase(); String value = Util.getInput("Enter '" + component + "' value: "); if (value == null || value.trim().length() == 0) { return null; } return component + "=" + value.trim(); }
/** * Sets the subject criterion. The specified distinguished name must match * the subject distinguished name in the <code>X509Certificate</code>. If * null, any subject distinguished name will do.<br /> * <br /> * If <code>subjectDN</code> is not <code>null</code>, it should * contain a single DER encoded distinguished name, as defined in X.501. For * the ASN.1 notation for this structure, see * {@link #setIssuer(byte []) setIssuer(byte [] issuerDN)}.<br /> * <br /> * Uses {@link org.bouncycastle.asn1.ASN1InputStream ASN1InputStream}, * {@link org.bouncycastle.asn1.ASN1Object ASN1Object}, * {@link org.bouncycastle.asn1.ASN1Sequence ASN1Sequence}, * {@link org.bouncycastle.asn1.x509.X509Name X509Name} * * @param subjectDN * a byte array containing the distinguished name in ASN.1 DER * format (or <code>null</code>) * * @exception IOException * if an encoding error occurs (incorrect form for DN) */ public void setSubject(byte[] subjectDN) throws IOException { if (subjectDN == null) { this.subjectDN = null; this.subjectDNX509 = null; } else { ByteArrayInputStream inStream = new ByteArrayInputStream(subjectDN); ASN1InputStream derInStream = new ASN1InputStream(inStream); ASN1Object obj = derInStream.readObject(); if (obj instanceof ASN1Sequence) { this.subjectDNX509 = new X509Name((ASN1Sequence)obj); } else { throw new IOException("parsing error"); } this.subjectDN = (byte[])subjectDN.clone(); } }
public static X509CRL createCRL(String provider, X509Certificate caCert, PrivateKey caKey, CRLEntry[] entries, Date expires, String signatureAlgorithm) throws Exception { X509V2CRLGenerator crlGen = new X509V2CRLGenerator(); Date now = new Date(); crlGen.setIssuerDN(new X509Name(caCert.getSubjectDN().getName())); crlGen.setThisUpdate(now); crlGen.setNextUpdate(expires); crlGen.setSignatureAlgorithm(signatureAlgorithm); for (int i = 0; i < entries.length; i++) { crlGen.addCRLEntry(entries[i].getCertificateSerialNumber(), now, entries[i].getReason()); } SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo((ASN1Sequence) new DERInputStream( new ByteArrayInputStream(caCert.getPublicKey().getEncoded())).readObject()); crlGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifier(apki)); crlGen.addExtension(X509Extensions.CRLNumber, false, new CRLNumber(BigInteger.valueOf(System .currentTimeMillis()))); return crlGen.generateX509CRL(caKey, provider); }
public CA(String dn) throws Exception { Security.addProvider(PROVIDER); Calendar c = new GregorianCalendar(); Date now = c.getTime(); c.add(Calendar.YEAR, 5); Date expires = c.getTime(); KeyPair pair = KeyUtil.generateRSAKeyPair512(PROVIDER.getName()); this.key = pair.getPrivate(); cert = CertUtil.generateCACertificate(PROVIDER.getName(), new X509Name(dn), now, expires, pair, SIGNATURE_ALGORITHM); if (PROVIDER.getName().equals("ERACOM")) { keyStore = KeyStore.getInstance("CRYPTOKI", PROVIDER.getName()); keyStore.load(null, PASSWORD.toCharArray()); keyStore.deleteEntry("CA"); keyStore.setKeyEntry("CA", this.key, null, new X509Certificate[]{cert}); key = (PrivateKey) keyStore.getKey("CA", null); } }
private void createCertifcateAuthorityCredentials(String dn, Date expirationDate, int keySize) throws CertificateAuthorityFault, NoCACredentialsFault { try { KeyPair pair = KeyUtil.generateRSAKeyPair(getCACredentialsProvider(), keySize); X509Certificate cacert = CertUtil.generateCACertificate(getCACredentialsProvider(), new X509Name(dn), new Date(), expirationDate, pair, getSignatureAlgorithm()); deleteCACredentials(); this.setCACredentials(cacert, pair.getPrivate(), properties.getCertificateAuthorityPassword()); } catch (Exception e) { logError(e.getMessage(), e); CertificateAuthorityFault fault = new CertificateAuthorityFault(); fault.setFaultString("Unexpected Error, could not create the CA credentials."); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (CertificateAuthorityFault) helper.getFault(); throw fault; } }
public void performTest() throws Exception { DistributionPointName name = new DistributionPointName( new GeneralNames(new GeneralName(new X509Name("cn=test")))); ReasonFlags reasonFlags = new ReasonFlags(ReasonFlags.cACompromise); checkPoint(6, name, true, true, reasonFlags, true, true); checkPoint(2, name, false, false, reasonFlags, false, false); checkPoint(0, null, false, false, null, false, false); try { IssuingDistributionPoint.getInstance(new Object()); fail("getInstance() failed to detect bad object."); } catch (IllegalArgumentException e) { // expected } }
public static X509Certificate generateCACertificate(String provider, X509Name subject, Date start, Date expired, KeyPair pair, int numberOfCAs, String signartureAlgorthm) throws InvalidKeyException, NoSuchProviderException, SignatureException, IOException { // generate the certificate X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setIssuerDN(subject); certGen.setNotBefore(start); certGen.setNotAfter(expired); certGen.setSubjectDN(subject); certGen.setPublicKey(pair.getPublic()); certGen.setSignatureAlgorithm(signartureAlgorthm); certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(numberOfCAs)); certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign)); SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo((ASN1Sequence) new DERInputStream( new ByteArrayInputStream(pair.getPublic().getEncoded())).readObject()); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifier(spki)); SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo((ASN1Sequence) new DERInputStream( new ByteArrayInputStream(pair.getPublic().getEncoded())).readObject()); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifier(apki)); return certGen.generateX509Certificate(pair.getPrivate(), provider); }
public Credential createIdentityCertificate(String id) throws Exception { String dn = getCertificate().getSubjectDN().getName(); int index = dn.indexOf("CN="); dn = dn.substring(0, index + 3) + id; KeyPair pair = KeyUtil.generateRSAKeyPair512(PROVIDER.getName()); Date now = new Date(); Date end = getCertificate().getNotAfter(); Credential cred = new Credential(CertUtil.generateCertificate(PROVIDER.getName(), new X509Name(dn), now, end, pair.getPublic(), getCertificate(), getPrivateKey(), SIGNATURE_ALGORITHM, null), pair.getPrivate()); if (PROVIDER.getName().equals("ERACOM")) { keyStore.deleteEntry(id); keyStore.setKeyEntry(id, cred.getPrivateKey(), null, new X509Certificate[]{cred.getCertificate()}); cred.setPrivateKey((PrivateKey) keyStore.getKey(id, null)); } return cred; }