Java Code Examples for org.bouncycastle.asn1.x509.GeneralName#otherName()

The following examples show how to use org.bouncycastle.asn1.x509.GeneralName#otherName() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestCertificateSignRequest.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
private void verifyServiceId(Extensions extensions) {
  GeneralNames gns =
      GeneralNames.fromExtensions(
          extensions, Extension.subjectAlternativeName);
  GeneralName[] names = gns.getNames();
  for(int i=0; i < names.length; i++) {
    if(names[i].getTagNo() == GeneralName.otherName) {
      ASN1Encodable asn1Encodable = names[i].getName();
      Iterator iterator = ((DLSequence) asn1Encodable).iterator();
      while (iterator.hasNext()) {
        Object o = iterator.next();
        if (o instanceof ASN1ObjectIdentifier) {
          String oid = o.toString();
          Assert.assertEquals(oid, "2.16.840.1.113730.3.1.34");
        }
        if (o instanceof DERTaggedObject) {
          String serviceName = ((DERTaggedObject)o).getObject().toString();
          Assert.assertEquals(serviceName, "OzoneMarketingCluster003");
        }
      }
    }
  }
}
 
Example 2
Source File: TlsHelperTest.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
private List<String> extractSanFromCsr(JcaPKCS10CertificationRequest csr) {
    List<String> sans = new ArrayList<>();
    Attribute[] certAttributes = csr.getAttributes();
    for (Attribute attribute : certAttributes) {
        if (attribute.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) {
            Extensions extensions = Extensions.getInstance(attribute.getAttrValues().getObjectAt(0));
            GeneralNames gns = GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName);
            GeneralName[] names = gns.getNames();
            for (GeneralName name : names) {
                logger.info("Type: " + name.getTagNo() + " | Name: " + name.getName());
                String title = "";
                if (name.getTagNo() == GeneralName.dNSName) {
                    title = "DNS";
                } else if (name.getTagNo() == GeneralName.iPAddress) {
                    title = "IP Address";
                    // name.toASN1Primitive();
                } else if (name.getTagNo() == GeneralName.otherName) {
                    title = "Other Name";
                }
                sans.add(title + ": " + name.getName());
            }
        }
    }

    return sans;
}
 
Example 3
Source File: CryptoTest.java    From athenz with Apache License 2.0 6 votes vote down vote up
@Test(dataProvider = "x500Principal")
public void testX509CSRrequest(String x500Principal, boolean badRequest) {
    PublicKey publicKey = Crypto.loadPublicKey(rsaPublicKey);
    PrivateKey privateKey = Crypto.loadPrivateKey(rsaPrivateKey);
    String certRequest = null;
    GeneralName otherName1 = new GeneralName(GeneralName.otherName, new DERIA5String("role1"));
    GeneralName otherName2 = new GeneralName(GeneralName.otherName, new DERIA5String("role2"));
    GeneralName[] sanArray = new GeneralName[]{otherName1, otherName2};
    try {
        certRequest = Crypto.generateX509CSR(privateKey, publicKey, x500Principal, sanArray);
    } catch (Exception e) {
        if (!badRequest) {
            fail("Should not have failed to create csr");
        }
    }
    if (!badRequest) {
        //Now validate the csr
        Crypto.getPKCS10CertRequest(certRequest);
    }
}
 
Example 4
Source File: CryptoTest.java    From athenz with Apache License 2.0 6 votes vote down vote up
@Test(dataProvider = "x500Principal")
public void testX509CSRrequestWithPrivateKeyOnly(String x500Principal, boolean badRequest) {
    PrivateKey privateKey = Crypto.loadPrivateKey(rsaPrivateKey);
    String certRequest = null;
    GeneralName otherName1 = new GeneralName(GeneralName.otherName, new DERIA5String("role1"));
    GeneralName otherName2 = new GeneralName(GeneralName.otherName, new DERIA5String("role2"));
    GeneralName[] sanArray = new GeneralName[]{otherName1, otherName2};
    try {
        certRequest = Crypto.generateX509CSR(privateKey, x500Principal, sanArray);
    } catch (Exception e) {
        if (!badRequest) {
            fail("Should not have failed to create csr");
        }
    }
    if (!badRequest) {
        //Now validate the csr
        Crypto.getPKCS10CertRequest(certRequest);
    }
}
 
Example 5
Source File: TlsHelperTest.java    From nifi with Apache License 2.0 6 votes vote down vote up
private List<String> extractSanFromCsr(JcaPKCS10CertificationRequest csr) {
    List<String> sans = new ArrayList<>();
    Attribute[] certAttributes = csr.getAttributes();
    for (Attribute attribute : certAttributes) {
        if (attribute.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) {
            Extensions extensions = Extensions.getInstance(attribute.getAttrValues().getObjectAt(0));
            GeneralNames gns = GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName);
            GeneralName[] names = gns.getNames();
            for (GeneralName name : names) {
                logger.info("Type: " + name.getTagNo() + " | Name: " + name.getName());
                String title = "";
                if (name.getTagNo() == GeneralName.dNSName) {
                    title = "DNS";
                } else if (name.getTagNo() == GeneralName.iPAddress) {
                    title = "IP Address";
                    // name.toASN1Primitive();
                } else if (name.getTagNo() == GeneralName.otherName) {
                    title = "Other Name";
                }
                sans.add(title + ": " + name.getName());
            }
        }
    }

    return sans;
}
 
Example 6
Source File: CertificateSignRequest.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
private CertificateSignRequest.Builder addAltName(int tag, String name) {
  if (altNames == null) {
    altNames = new ArrayList<>();
  }
  if (tag == GeneralName.otherName) {
    ASN1Object ono = addOtherNameAsn1Object(name);

    altNames.add(new GeneralName(tag, ono));
  } else {
    altNames.add(new GeneralName(tag, name));
  }
  return this;
}
 
Example 7
Source File: CertificateManagerTest.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * {@link CertificateManager#getServerIdentities(X509Certificate)} should return:
 * <ul>
 *     <li>the 'xmppAddr' subjectAltName value</li>
 *     <li>explicitly not the Common Name</li>
 * </ul>
 *
 * when a certificate contains:
 * <ul>
 *     <li>a subjectAltName entry of type otherName with an ASN.1 Object Identifier of "id-on-xmppAddr"</li>
 * </ul>
 */
@Test
public void testServerIdentitiesXmppAddr() throws Exception
{
    // Setup fixture.
    final String subjectCommonName = "MySubjectCommonName";
    final String subjectAltNameXmppAddr = "MySubjectAltNameXmppAddr";

    final X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(
            new X500Name( "CN=MyIssuer" ),                                          // Issuer
            BigInteger.valueOf( Math.abs( new SecureRandom().nextInt() ) ),         // Random serial number
            new Date( System.currentTimeMillis() - ( 1000L * 60 * 60 * 24 * 30 ) ), // Not before 30 days ago
            new Date( System.currentTimeMillis() + ( 1000L * 60 * 60 * 24 * 99 ) ), // Not after 99 days from now
            new X500Name( "CN=" + subjectCommonName ),                              // Subject
            subjectKeyPair.getPublic()
    );

    final DERSequence otherName = new DERSequence( new ASN1Encodable[] { XMPP_ADDR_OID, new DERUTF8String( subjectAltNameXmppAddr ) });
    final GeneralNames subjectAltNames = new GeneralNames( new GeneralName(GeneralName.otherName, otherName ) );
    builder.addExtension( Extension.subjectAlternativeName, true, subjectAltNames );

    final X509CertificateHolder certificateHolder = builder.build( contentSigner );
    final X509Certificate cert = new JcaX509CertificateConverter().getCertificate( certificateHolder );

    // Execute system under test
    final List<String> serverIdentities = CertificateManager.getServerIdentities( cert );

    // Verify result
    assertEquals( 1, serverIdentities.size() );
    assertTrue( serverIdentities.contains( subjectAltNameXmppAddr ));
    assertFalse( serverIdentities.contains( subjectCommonName ) );
}
 
Example 8
Source File: CertificateManagerTest.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * {@link CertificateManager#getServerIdentities(X509Certificate)} should return:
 * <ul>
 *     <li>the 'DNS SRV' subjectAltName value</li>
 *     <li>explicitly not the Common Name</li>
 * </ul>
 *
 * when a certificate contains:
 * <ul>
 *     <li>a subjectAltName entry of type otherName with an ASN.1 Object Identifier of "id-on-dnsSRV"</li>
 * </ul>
 */
@Test
public void testServerIdentitiesDnsSrv() throws Exception
{
    // Setup fixture.
    final String subjectCommonName = "MySubjectCommonName";
    final String subjectAltNameDnsSrv = "MySubjectAltNameXmppAddr";

    final X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(
            new X500Name( "CN=MyIssuer" ),                                          // Issuer
            BigInteger.valueOf( Math.abs( new SecureRandom().nextInt() ) ),         // Random serial number
            new Date( System.currentTimeMillis() - ( 1000L * 60 * 60 * 24 * 30 ) ), // Not before 30 days ago
            new Date( System.currentTimeMillis() + ( 1000L * 60 * 60 * 24 * 99 ) ), // Not after 99 days from now
            new X500Name( "CN=" + subjectCommonName ),                              // Subject
            subjectKeyPair.getPublic()
    );

    final DERSequence otherName = new DERSequence( new ASN1Encodable[] {DNS_SRV_OID, new DERUTF8String( "_xmpp-server."+subjectAltNameDnsSrv ) });
    final GeneralNames subjectAltNames = new GeneralNames( new GeneralName(GeneralName.otherName, otherName ) );
    builder.addExtension( Extension.subjectAlternativeName, true, subjectAltNames );

    final X509CertificateHolder certificateHolder = builder.build( contentSigner );
    final X509Certificate cert = new JcaX509CertificateConverter().getCertificate( certificateHolder );

    // Execute system under test
    final List<String> serverIdentities = CertificateManager.getServerIdentities( cert );

    // Verify result
    assertEquals( 1, serverIdentities.size() );
    assertTrue( serverIdentities.contains( subjectAltNameDnsSrv ));
    assertFalse( serverIdentities.contains( subjectCommonName ) );
}
 
Example 9
Source File: CertificateManagerTest.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * {@link CertificateManager#getServerIdentities(X509Certificate)} should return:
 * <ul>
 *     <li>the DNS subjectAltName value</li>
 *     <li>the 'xmppAddr' subjectAltName value</li>
 *     <li>explicitly not the Common Name</li>
 * </ul>
 *
 * when a certificate contains:
 * <ul>
 *     <li>a subjectAltName entry of type DNS </li>
 *     <li>a subjectAltName entry of type otherName with an ASN.1 Object Identifier of "id-on-xmppAddr"</li>
 * </ul>
 */
@Test
public void testServerIdentitiesXmppAddrAndDNS() throws Exception
{
    // Setup fixture.
    final String subjectCommonName = "MySubjectCommonName";
    final String subjectAltNameXmppAddr = "MySubjectAltNameXmppAddr";
    final String subjectAltNameDNS = "MySubjectAltNameDNS";

    final X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(
            new X500Name( "CN=MyIssuer" ),                                          // Issuer
            BigInteger.valueOf( Math.abs( new SecureRandom().nextInt() ) ),         // Random serial number
            new Date( System.currentTimeMillis() - ( 1000L * 60 * 60 * 24 * 30 ) ), // Not before 30 days ago
            new Date( System.currentTimeMillis() + ( 1000L * 60 * 60 * 24 * 99 ) ), // Not after 99 days from now
            new X500Name( "CN=" + subjectCommonName ),                              // Subject
            subjectKeyPair.getPublic()
    );

    final DERSequence otherName = new DERSequence( new ASN1Encodable[] { XMPP_ADDR_OID, new DERUTF8String( subjectAltNameXmppAddr ) });
    final GeneralNames subjectAltNames = new GeneralNames( new GeneralName[] {
            new GeneralName( GeneralName.otherName, otherName ),
            new GeneralName( GeneralName.dNSName, subjectAltNameDNS )
    });
    builder.addExtension( Extension.subjectAlternativeName, true, subjectAltNames );

    final X509CertificateHolder certificateHolder = builder.build( contentSigner );
    final X509Certificate cert = new JcaX509CertificateConverter().getCertificate( certificateHolder );

    // Execute system under test
    final List<String> serverIdentities = CertificateManager.getServerIdentities( cert );

    // Verify result
    assertEquals( 2, serverIdentities.size() );
    assertTrue( serverIdentities.contains( subjectAltNameXmppAddr ));
    assertFalse( serverIdentities.contains( subjectCommonName ) );
}
 
Example 10
Source File: DefaultProfile.java    From hadoop-ozone with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public boolean validateGeneralName(int type, String value) {
  // TODO : We should add more validation for IP address, for example
  //  it matches the local network, and domain matches where the cluster
  //  exits.
  if (!isSupportedGeneralName(type)) {
    return false;
  }
  switch (type) {
  case GeneralName.iPAddress:

    // We need DatatypeConverter conversion, since the original CSR encodes
    // an IP address int a Hex String, for example 8.8.8.8 is encoded as
    // #08080808. Value string is always preceded by "#", we will strip
    // that before passing it on.

    // getByAddress call converts the IP address to hostname/ipAddress format.
    // if the hostname cannot determined then it will be /ipAddress.

    // TODO: Fail? if we cannot resolve the Hostname?
    try {
      final InetAddress byAddress = InetAddress.getByAddress(
          Hex.decodeHex(value.substring(1)));
      if (LOG.isDebugEnabled()) {
        LOG.debug("Host Name/IP Address : {}", byAddress.toString());
      }
      return true;
    } catch (UnknownHostException | DecoderException e) {
      return false;
    }
  case GeneralName.dNSName:
    return DomainValidator.getInstance().isValid(value);
  case GeneralName.otherName:
    // for other name its a general string, nothing to validate
    return true;
  default:
    // This should not happen, since it guarded via isSupportedGeneralName.
    LOG.error("Unexpected type in General Name (int value) : {}", type);
    return false;
  }
}
 
Example 11
Source File: DGeneralNameChooser.java    From keystore-explorer with GNU General Public License v3.0 4 votes vote down vote up
private void populate(GeneralName generalName) {
	if (generalName == null) {
		jrbDirectoryName.setSelected(true);
	} else {
		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;
		}
		}
	}
}