List of usage examples for org.bouncycastle.asn1.x509 GeneralName rfc822Name
int rfc822Name
To view the source code for org.bouncycastle.asn1.x509 GeneralName rfc822Name.
Click Source Link
From source file:io.aos.crypto.spl06.X509V3CreateExample.java
License:Apache License
public static X509Certificate generateV3Certificate(KeyPair pair) throws InvalidKeyException, NoSuchProviderException, SignatureException { // generate the certificate X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setIssuerDN(new X500Principal("CN=Test Certificate")); certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000)); certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000)); certGen.setSubjectDN(new X500Principal("CN=Test Certificate")); certGen.setPublicKey(pair.getPublic()); certGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); certGen.addExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth)); certGen.addExtension(X509Extensions.SubjectAlternativeName, false, new GeneralNames(new GeneralName(GeneralName.rfc822Name, "test@test.test"))); return certGen.generateX509Certificate(pair.getPrivate(), "BC"); }
From source file:krypto.KryptoService.java
License:Apache License
/** * Erzeugt ein x509 v3-Zertifikat, das 1 Tag lang gltig ist. * @return/*from w w w .j ava2 s. co m*/ * @throws Exception */ public static X509Certificate generateCertificate(String algorithm) { X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); KeyPair pair = null; try { pair = generateKeyPair(algorithm, 1024); } catch (Exception e) { try { pair = generateKeyPair(algorithm, 512); } catch (Exception e2) { System.out.println(e2.getMessage()); } } long day = 24 * 60 * 60 * 1000; // 1 Tag gltig certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setIssuerDN(new X509Name(new X500Principal("CN=Test Certificate").getName())); certGen.setNotBefore(new Date(System.currentTimeMillis() - 500000)); certGen.setNotAfter(new Date(System.currentTimeMillis() + day)); certGen.setSubjectDN(new X509Name(new X500Principal("CN=Test Certificate").getName())); certGen.setPublicKey(pair.getPublic()); certGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); certGen.addExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth)); certGen.addExtension(X509Extensions.SubjectAlternativeName, false, new GeneralNames(new GeneralName(GeneralName.rfc822Name, "test@test.test"))); X509Certificate cert = null; try { cert = certGen.generate(pair.getPrivate(), "BC"); } catch (CertificateEncodingException e) { System.out.println("CertificateEncodingException"); } catch (InvalidKeyException e2) { System.out.println("InvalidKeyException: " + e2.getMessage()); } catch (Exception e3) { // do nothing } return cert; }
From source file:net.java.bd.tools.security.SecurityUtil.java
License:Open Source License
GeneralNames getRfc822Name(String name) { GeneralName gn = new GeneralName(GeneralName.rfc822Name, new DERIA5String(name)); DERConstructedSequence seq = new DERConstructedSequence(); seq.addObject(gn);// ww w . j a v a2 s. c o m return new GeneralNames(seq); }
From source file:net.laubenberger.bogatyr.service.crypto.CertificateProviderImpl.java
License:Open Source License
@Override public X509Certificate generateCertificate(final KeyPair pair, final String issuerDN, final String subjectDN, final String generalName, final Date start, final Date end) throws NoSuchAlgorithmException, IllegalStateException, CertificateEncodingException, InvalidKeyException, NoSuchProviderException, SecurityException, SignatureException { //$JUnit$ if (null == pair) { throw new RuntimeExceptionIsNull("pair"); //$NON-NLS-1$ }//from ww w . j a va2 s .c om if (null == issuerDN) { throw new RuntimeExceptionIsNull("issuerDN"); //$NON-NLS-1$ } if (!HelperString.isValid(issuerDN)) { throw new RuntimeExceptionIsEmpty("issuerDN"); //$NON-NLS-1$ } if (null == subjectDN) { throw new RuntimeExceptionIsNull("subjectDN"); //$NON-NLS-1$ } if (!HelperString.isValid(subjectDN)) { throw new RuntimeExceptionIsEmpty("subjectDN"); //$NON-NLS-1$ } if (null == generalName) { throw new RuntimeExceptionIsNull("generalName"); //$NON-NLS-1$ } if (!HelperString.isValid(generalName)) { throw new RuntimeExceptionIsEmpty("generalName"); //$NON-NLS-1$ } if (null == start) { throw new RuntimeExceptionIsNull("start"); //$NON-NLS-1$ } if (null == end) { throw new RuntimeExceptionIsNull("end"); //$NON-NLS-1$ } if (start.after(end)) { throw new RuntimeExceptionMustBeBefore("start", start, end); //$NON-NLS-1$ } // generate the certificate final X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setIssuerDN(new X500Principal(issuerDN)); certGen.setNotBefore(start); certGen.setNotAfter(end); certGen.setSubjectDN(new X500Principal(subjectDN)); certGen.setPublicKey(pair.getPublic()); certGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); //$NON-NLS-1$ certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); certGen.addExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth)); certGen.addExtension(X509Extensions.SubjectAlternativeName, false, new GeneralNames(new GeneralName(GeneralName.rfc822Name, generalName))); return certGen.generate(pair.getPrivate(), provider.getName()); }
From source file:net.sf.keystore_explorer.crypto.x509.GeneralNameUtil.java
License:Open Source License
/** * Get string representation for General names that cannot cause a * IOException to be thrown. Unsupported are ediPartyName, otherName and * x400Address. Returns a blank string for these. * * @param generalName/* w ww. j a v a 2 s . c o m*/ * General name * @param addLinkForURI * If true, convert URI to a clickable link * @return String representation of general name */ public static String safeToString(GeneralName generalName, boolean addLinkForURI) { if (generalName == null) { return ""; } switch (generalName.getTagNo()) { case GeneralName.directoryName: { X500Name directoryName = (X500Name) generalName.getName(); return MessageFormat.format(res.getString("GeneralNameUtil.DirectoryGeneralName"), directoryName.toString()); } case GeneralName.dNSName: { DERIA5String dnsName = (DERIA5String) generalName.getName(); return MessageFormat.format(res.getString("GeneralNameUtil.DnsGeneralName"), dnsName.getString()); } case GeneralName.iPAddress: { byte[] ipAddressBytes = ((ASN1OctetString) generalName.getName()).getOctets(); String ipAddressString = ""; try { ipAddressString = InetAddress.getByAddress(ipAddressBytes).getHostAddress(); } catch (UnknownHostException e) { // ignore -> results in empty IP address string } return MessageFormat.format(res.getString("GeneralNameUtil.IpAddressGeneralName"), ipAddressString); } case GeneralName.registeredID: { ASN1ObjectIdentifier registeredId = (ASN1ObjectIdentifier) generalName.getName(); return MessageFormat.format(res.getString("GeneralNameUtil.RegisteredIdGeneralName"), ObjectIdUtil.toString(registeredId)); } case GeneralName.rfc822Name: { DERIA5String rfc822Name = (DERIA5String) generalName.getName(); return MessageFormat.format(res.getString("GeneralNameUtil.Rfc822GeneralName"), rfc822Name.getString()); } case GeneralName.uniformResourceIdentifier: { DERIA5String uri = (DERIA5String) generalName.getName(); String link = addLinkForURI ? "<html><a href=\"" + uri.getString() + "\">" + uri.getString() + "</a></html>" : uri.getString(); return MessageFormat.format(res.getString("GeneralNameUtil.UriGeneralName"), link); } case GeneralName.otherName: { // we currently only support UPN in otherName String upn = parseUPN(generalName); return MessageFormat.format(res.getString("GeneralNameUtil.OtherGeneralName"), "UPN", upn); } default: { return ""; } } }
From source file:net.sf.keystore_explorer.gui.crypto.generalname.DGeneralNameChooser.java
License:Open Source License
private void populate(GeneralName generalName) { if (generalName == null) { jrbDirectoryName.setSelected(true); } else {/* w w w .ja va 2 s. co m*/ switch (generalName.getTagNo()) { case GeneralName.directoryName: { jrbDirectoryName.setSelected(true); jdnDirectoryName.setDistinguishedName((X500Name) generalName.getName()); break; } case GeneralName.dNSName: { jrbDnsName.setSelected(true); jtfDnsName.setText(((DERIA5String) generalName.getName()).getString()); break; } case GeneralName.iPAddress: { jrbIpAddress.setSelected(true); byte[] ipAddressBytes = ((ASN1OctetString) generalName.getName()).getOctets(); try { jtfIpAddress.setText(InetAddress.getByAddress(ipAddressBytes).getHostAddress()); } catch (UnknownHostException e) { // cannot happen here because user input was checked for validity } break; } case GeneralName.registeredID: { jrbRegisteredId.setSelected(true); joiRegisteredId.setObjectId((ASN1ObjectIdentifier) generalName.getName()); break; } case GeneralName.rfc822Name: { jrbRfc822Name.setSelected(true); jtfRfc822Name.setText(((DERIA5String) generalName.getName()).getString()); break; } case GeneralName.uniformResourceIdentifier: { jrbUniformResourceIdentifier.setSelected(true); jtfUniformResourceIdentifier.setText(((DERIA5String) generalName.getName()).getString()); break; } case GeneralName.otherName: { jrbPrincipalName.setSelected(true); // we currently only support UPN in otherName jtfPrincipalName.setText(GeneralNameUtil.parseUPN(generalName)); break; } } } }
From source file:net.sf.keystore_explorer.gui.crypto.generalname.DGeneralNameChooser.java
License:Open Source License
private void okPressed() { try {/*from www . j a v a 2s.c om*/ GeneralName newGeneralName = null; if (jrbDirectoryName.isSelected()) { X500Name directoryName = jdnDirectoryName.getDistinguishedName(); if (directoryName == null) { JOptionPane.showMessageDialog(this, res.getString("DGeneralNameChooser.DirectoryNameValueReq.message"), getTitle(), JOptionPane.WARNING_MESSAGE); return; } newGeneralName = new GeneralName(GeneralName.directoryName, directoryName); } else if (jrbDnsName.isSelected()) { String dnsName = jtfDnsName.getText().trim(); if (dnsName.length() == 0) { JOptionPane.showMessageDialog(this, res.getString("DGeneralNameChooser.DnsNameValueReq.message"), getTitle(), JOptionPane.WARNING_MESSAGE); return; } newGeneralName = new GeneralName(GeneralName.dNSName, new DERIA5String(dnsName)); } else if (jrbIpAddress.isSelected()) { String ipAddress = jtfIpAddress.getText().trim(); if (ipAddress.length() == 0) { JOptionPane.showMessageDialog(this, res.getString("DGeneralNameChooser.IpAddressValueReq.message"), getTitle(), JOptionPane.WARNING_MESSAGE); return; } if (!IPAddress.isValid(ipAddress)) { JOptionPane.showMessageDialog(this, res.getString("DGeneralNameChooser.NotAValidIP.message"), getTitle(), JOptionPane.WARNING_MESSAGE); return; } newGeneralName = new GeneralName(GeneralName.iPAddress, ipAddress); } else if (jrbRegisteredId.isSelected()) { ASN1ObjectIdentifier registeredId = joiRegisteredId.getObjectId(); if (registeredId == null) { JOptionPane.showMessageDialog(this, res.getString("DGeneralNameChooser.RegisteredIdValueReq.message"), getTitle(), JOptionPane.WARNING_MESSAGE); return; } newGeneralName = new GeneralName(GeneralName.registeredID, registeredId); } else if (jrbRfc822Name.isSelected()) { String rfc822Name = jtfRfc822Name.getText().trim(); if (rfc822Name.length() == 0) { JOptionPane.showMessageDialog(this, res.getString("DGeneralNameChooser.Rfc822NameValueReq.message"), getTitle(), JOptionPane.WARNING_MESSAGE); return; } newGeneralName = new GeneralName(GeneralName.rfc822Name, new DERIA5String(rfc822Name)); } else if (jrbUniformResourceIdentifier.isSelected()) { String uniformResourceIdentifier = jtfUniformResourceIdentifier.getText().trim(); if (uniformResourceIdentifier.length() == 0) { JOptionPane.showMessageDialog(this, res.getString("DGeneralNameChooser.UniformResourceIdentifierValueReq.message"), getTitle(), JOptionPane.WARNING_MESSAGE); return; } newGeneralName = new GeneralName(GeneralName.uniformResourceIdentifier, new DERIA5String(uniformResourceIdentifier)); } else if (jrbPrincipalName.isSelected()) { String upnString = jtfPrincipalName.getText().trim(); if (upnString.length() == 0) { JOptionPane.showMessageDialog(this, res.getString("DGeneralNameChooser.PrincipalNameValueReq.message"), getTitle(), JOptionPane.WARNING_MESSAGE); return; } ASN1EncodableVector asn1Vector = new ASN1EncodableVector(); asn1Vector.add(new ASN1ObjectIdentifier(GeneralNameUtil.UPN_OID)); asn1Vector.add(new DERTaggedObject(true, 0, new DERUTF8String(upnString))); newGeneralName = new GeneralName(GeneralName.otherName, new DERSequence(asn1Vector)); } generalName = newGeneralName; } catch (Exception ex) { DError dError = new DError(this, ex); dError.setLocationRelativeTo(this); dError.setVisible(true); return; } closeDialog(); }
From source file:net.sf.portecle.crypto.X509Ext.java
License:Open Source License
/** * Get the supplied general name as a string ([general name type]=[general name]). * /*from w w w .j a v a 2s . c om*/ * <pre> * GeneralName ::= CHOICE { * otherName [0] OtherName, * rfc822Name [1] IA5String, x * dNSName [2] IA5String, x * x400Address [3] ORAddress, * directoryName [4] Name, x * ediPartyName [5] EDIPartyName, * uniformResourceIdentifier [6] IA5String, x * iPAddress [7] OCTET STRING, x * registeredID [8] OBJECT IDENTIFIER x } * OtherName ::= SEQUENCE { * type-id OBJECT IDENTIFIER, * value [0] EXPLICIT ANY DEFINED BY type-id } * EDIPartyName ::= SEQUENCE { * nameAssigner [0] DirectoryString OPTIONAL, * partyName [1] DirectoryString } * DirectoryString ::= CHOICE { * teletexString TeletexString (SIZE (1..maxSize), * printableString PrintableString (SIZE (1..maxSize)), * universalString UniversalString (SIZE (1..maxSize)), * utf8String UTF8String (SIZE (1.. MAX)), * bmpString BMPString (SIZE(1..maxSIZE)) } * </pre> * * @param generalName The general name * @return General name string * @throws IOException */ private String getGeneralNameString(GeneralName generalName, LinkClass linkClass) throws IOException { StringBuilder strBuff = new StringBuilder(); int tagNo = generalName.getTagNo(); switch (tagNo) { case GeneralName.otherName: ASN1Sequence other = (ASN1Sequence) generalName.getName(); String sOid = ((ASN1ObjectIdentifier) other.getObjectAt(0)).getId(); String sVal = stringify(other.getObjectAt(1)); try { strBuff.append(RB.getString(sOid)); } catch (MissingResourceException e) { strBuff.append(MessageFormat.format(RB.getString("GeneralName." + tagNo), sOid)); } strBuff.append(": "); strBuff.append(sVal); break; case GeneralName.rfc822Name: String sRfc822 = generalName.getName().toString(); String urlEnc = URLEncoder.encode(sRfc822, "UTF-8"); strBuff.append(RB.getString("GeneralName." + tagNo)); strBuff.append(": "); strBuff.append(getLink("mailto:" + urlEnc, escapeHtml(sRfc822), null)); break; case GeneralName.dNSName: case GeneralName.registeredID: case GeneralName.x400Address: // TODO: verify formatting case GeneralName.ediPartyName: // TODO: verify formatting strBuff.append(RB.getString("GeneralName." + tagNo)); strBuff.append(": "); strBuff.append(escapeHtml(generalName.getName())); break; case GeneralName.directoryName: ASN1Encodable name = generalName.getName(); strBuff.append(RB.getString("GeneralName." + tagNo)); strBuff.append(": "); // TODO: make E=foo@bar.com mail links strBuff.append(escapeHtml(name)); break; case GeneralName.uniformResourceIdentifier: String sUri = generalName.getName().toString(); strBuff.append(RB.getString("GeneralName." + tagNo)); strBuff.append(": "); strBuff.append(getLink(sUri, escapeHtml(sUri), linkClass)); break; case GeneralName.iPAddress: ASN1OctetString ipAddress = (ASN1OctetString) generalName.getName(); byte[] bIpAddress = ipAddress.getOctets(); // Output the IP Address components one at a time separated by dots StringBuilder sbIpAddress = new StringBuilder(); for (int iCnt = 0, bl = bIpAddress.length; iCnt < bl; iCnt++) { // Convert from (possibly negative) byte to positive int sbIpAddress.append(bIpAddress[iCnt] & 0xFF); if ((iCnt + 1) < bIpAddress.length) { sbIpAddress.append('.'); } } strBuff.append(RB.getString("GeneralName." + tagNo)); strBuff.append(": "); strBuff.append(escapeHtml(sbIpAddress)); break; default: // Unsupported general name type strBuff.append( MessageFormat.format(RB.getString("UnrecognizedGeneralNameType"), generalName.getTagNo())); strBuff.append(": "); strBuff.append(escapeHtml(generalName.getName())); break; } return strBuff.toString(); }
From source file:org.apache.jmeter.assertions.SMIMEAssertion.java
License:Apache License
/** * Extract email addresses from a certificate * /*ww w.j a va 2 s .com*/ * @param cert the X509 certificate holder * @return a List of all email addresses found * @throws CertificateException */ private static List<String> getEmailFromCert(X509CertificateHolder cert) throws CertificateException { List<String> res = new ArrayList<>(); X500Name subject = cert.getSubject(); for (RDN emails : subject.getRDNs(BCStyle.EmailAddress)) { for (AttributeTypeAndValue emailAttr : emails.getTypesAndValues()) { log.debug("Add email from RDN: " + IETFUtils.valueToString(emailAttr.getValue())); res.add(IETFUtils.valueToString(emailAttr.getValue())); } } Extension subjectAlternativeNames = cert.getExtension(Extension.subjectAlternativeName); if (subjectAlternativeNames != null) { for (GeneralName name : GeneralNames.getInstance(subjectAlternativeNames.getParsedValue()).getNames()) { if (name.getTagNo() == GeneralName.rfc822Name) { String email = IETFUtils.valueToString(name.getName()); log.debug("Add email from subjectAlternativeName: " + email); res.add(email); } } } return res; }
From source file:org.candlepin.resource.test.cert.test.CertTest.java
License:Open Source License
@Test public void testCertExample() throws Exception { Security.addProvider(new BouncyCastleProvider()); ////from w ww. j a v a 2 s . com // set up the keys // KeyFactory fact = KeyFactory.getInstance("RSA", "BC"); PrivateKey caPrivKey = fact.generatePrivate(caPrivKeySpec); PublicKey caPubKey = fact.generatePublic(caPubKeySpec); //PrivateKey privKey = fact.generatePrivate(privKeySpec); PublicKey pubKey = fact.generatePublic(pubKeySpec); // // note in this case we are using the CA certificate for both the client // cetificate // and the attribute certificate. This is to make the vcode simpler to // read, in practice // the CA for the attribute certificate should be different to that of // the client certificate // X509Certificate caCert = AttrCertExample.createAcIssuerCert(caPubKey, caPrivKey); X509Certificate clientCert = AttrCertExample.createClientCert(pubKey, caPrivKey, caPubKey); // Instantiate a new AC generator X509V2AttributeCertificateGenerator acGen = new X509V2AttributeCertificateGenerator(); acGen.reset(); // // Holder: here we use the IssuerSerial form // acGen.setHolder(new AttributeCertificateHolder(clientCert)); // set the Issuer acGen.setIssuer(new AttributeCertificateIssuer(caCert.getSubjectX500Principal())); // // serial number (as it's an example we don't have to keep track of the // serials anyway // acGen.setSerialNumber(BigInteger.ONE); // not Before acGen.setNotBefore(new Date(System.currentTimeMillis() - 50000)); // not After acGen.setNotAfter(new Date(System.currentTimeMillis() + 50000)); // signature Algorithmus acGen.setSignatureAlgorithm("SHA1WithRSAEncryption"); // the actual attributes GeneralName roleName = new GeneralName(GeneralName.rfc822Name, "DAU123456789"); ASN1EncodableVector roleSyntax = new ASN1EncodableVector(); roleSyntax.add(roleName); // roleSyntax OID: 2.5.24.72 X509Attribute attributes = new X509Attribute("2.5.24.72", new DERSequence(roleSyntax)); acGen.addAttribute(attributes); // finally create the AC X509V2AttributeCertificate att = (X509V2AttributeCertificate) acGen.generate(caPrivKey, "BC"); //String encoded = new String(att.getEncoded()); //System.out.println("CERT CERT: " + encoded); //KeyStore store = KeyStore.getInstance("PKCS12"); //String pass = "redhat"; /*FileOutputStream fout = new FileOutputStream("/tmp/foo.file"); store.load(null, null); store.store(fout, pass.toCharArray()); X509CertificateObject ccert = new X509CertificateObject(new X509CertificateStructure(new DERSequence(att)));*/ // // starting here, we parse the newly generated AC // // Holder AttributeCertificateHolder h = att.getHolder(); if (h.match(clientCert)) { if (h.getEntityNames() != null) { // System.out.println(h.getEntityNames().length + // " entity names found"); } if (h.getIssuer() != null) { // System.out.println(h.getIssuer().length + // " issuer names found, serial number " + // h.getSerialNumber()); } // System.out.println("Matches original client x509 cert"); } // Issuer AttributeCertificateIssuer issuer = att.getIssuer(); if (issuer.match(caCert)) { if (issuer.getPrincipals() != null) { // System.out.println(issuer.getPrincipals().length + // " entity names found"); } // System.out.println("Matches original ca x509 cert"); } // Dates // System.out.println("valid not before: " + att.getNotBefore()); // System.out.println("valid not before: " + att.getNotAfter()); // check the dates, an exception is thrown in checkValidity()... try { att.checkValidity(); att.checkValidity(new Date()); } catch (Exception e) { System.out.println(e); } // verify try { att.verify(caPubKey, "BC"); } catch (Exception e) { System.out.println(e); } // Attribute X509Attribute[] attribs = att.getAttributes(); // System.out.println("cert has " + attribs.length + " attributes:"); for (int i = 0; i < attribs.length; i++) { X509Attribute a = attribs[i]; // System.out.println("OID: " + a.getOID()); // currently we only check for the presence of a 'RoleSyntax' // attribute if (a.getOID().equals("2.5.24.72")) { // System.out.println("rolesyntax read from cert!"); } } }