Java Code Examples for org.bouncycastle.asn1.x500.X500Name#getInstance()

The following examples show how to use org.bouncycastle.asn1.x500.X500Name#getInstance() . 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: SignatureCmpCaClient.java    From xipki with Apache License 2.0 6 votes vote down vote up
public SignatureCmpCaClient(String caUri, X509Certificate caCert, PrivateKey requestorKey,
    X509Certificate requestorCert, X509Certificate responderCert, String hashAlgo)
    throws Exception {
  super(caUri, caCert,
      X500Name.getInstance(requestorCert.getSubjectX500Principal().getEncoded()),
      X500Name.getInstance(responderCert.getSubjectX500Principal().getEncoded()),
      hashAlgo);

  this.requestorKey = SdkUtil.requireNonNull("requestorKey", requestorKey);
  SdkUtil.requireNonNull("requestorCert", requestorCert);

  this.responderCert = SdkUtil.requireNonNull("responderCert", responderCert);
  this.requestorSigner = buildSigner(requestorKey);

  ASN1ObjectIdentifier[] oids = {PKCSObjectIdentifiers.sha256WithRSAEncryption,
    PKCSObjectIdentifiers.sha384WithRSAEncryption, PKCSObjectIdentifiers.sha512WithRSAEncryption,
    X9ObjectIdentifiers.ecdsa_with_SHA256, X9ObjectIdentifiers.ecdsa_with_SHA384,
    X9ObjectIdentifiers.ecdsa_with_SHA512, NISTObjectIdentifiers.dsa_with_sha256,
    NISTObjectIdentifiers.dsa_with_sha384, NISTObjectIdentifiers.dsa_with_sha512};
  for (ASN1ObjectIdentifier oid : oids) {
    trustedProtectionAlgOids.add(oid.getId());
  }
}
 
Example 2
Source File: CmpCaClient.java    From xipki with Apache License 2.0 6 votes vote down vote up
public CmpCaClient(String caUri, X509Certificate caCert, X500Name requestorSubject,
    X500Name responderSubject, String hashAlgo) throws Exception {
  this.caUri = SdkUtil.requireNonBlank("caUri", caUri);
  this.caUrl = new URL(this.caUri);
  this.hashAlgo = (hashAlgo == null) ? "SHA256" : hashAlgo;

  this.random = new SecureRandom();

  this.requestorSubject = new GeneralName(requestorSubject);
  this.responderSubject = new GeneralName(responderSubject);

  if (caCert != null) {
    this.caCert = caCert;
    this.caSubject = X500Name.getInstance(caCert.getSubjectX500Principal().getEncoded());
    this.caSubjectKeyIdentifier = SdkUtil.extractSki(caCert);
  }
}
 
Example 3
Source File: CmpResponder.java    From xipki with Apache License 2.0 6 votes vote down vote up
@Override
protected boolean intendsMe(GeneralName requestRecipient) {
  if (requestRecipient == null) {
    return false;
  }

  if (getSender().equals(requestRecipient)) {
    return true;
  }

  if (requestRecipient.getTagNo() == GeneralName.directoryName) {
    X500Name x500Name = X500Name.getInstance(requestRecipient.getName());
    if (x500Name.equals(caManager.getSignerWrapper(getResponderName()).getSubject())) {
      return true;
    }
  }

  return false;
}
 
Example 4
Source File: OcspRef.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
private String getResponderIdByName() {
   RespID responderId = this.ocsp.getResponderId();
   ResponderID responderIdAsASN1Object = responderId.toASN1Primitive();
   DERTaggedObject derTaggedObject = (DERTaggedObject)responderIdAsASN1Object.toASN1Primitive();
   if (2 == derTaggedObject.getTagNo()) {
      return null;
   } else {
      ASN1Primitive derObject = derTaggedObject.getObject();
      X500Name name = X500Name.getInstance(derObject);
      return RFC2253Parser.normalize(name.toString());
   }
}
 
Example 5
Source File: DHSigStaticKeyCertPair.java    From xipki with Apache License 2.0 5 votes vote down vote up
public DHSigStaticKeyCertPair(PrivateKey privateKey, X509Cert certificate) {
  this.privateKey = Args.notNull(privateKey, "privateKey");
  Args.notNull(certificate, "certificate");
  this.serialNumber = certificate.getSerialNumber();
  try {
    this.encodedIssuer = certificate.getIssuer().getEncoded();
    this.encodedSubject = certificate.getSubject().getEncoded();
  } catch (Exception ex) {
    throw new IllegalArgumentException("error encoding certificate", ex);
  }
  this.issuer = X500Name.getInstance(this.encodedIssuer);
  this.subject = X500Name.getInstance(this.encodedSubject);
}
 
Example 6
Source File: X509Cert.java    From xipki with Apache License 2.0 5 votes vote down vote up
public X509Cert(X509Certificate cert, byte[] encoded) {
  this.bcInstance = null;
  this.jceInstance = Args.notNull(cert, "cert");
  this.encoded = encoded;

  this.notBefore = cert.getNotBefore();
  this.notAfter = cert.getNotAfter();
  this.serialNumber = cert.getSerialNumber();

  this.issuer = X500Name.getInstance(cert.getIssuerX500Principal().getEncoded());
  this.subject = X500Name.getInstance(cert.getSubjectX500Principal().getEncoded());

  this.selfSigned = subject.equals(issuer);
}
 
Example 7
Source File: CertificateIdentifier.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Returns DER-encoded IssuerSerial representation of the object.
 * NOTE: the issuerName and SerialNumber must be defined! Returns null in the opposite case
 * 
 * @return a byte array of the encoded IssuerSerial
 */
public byte[] getIssuerSerialEncoded() {
	if (issuerName != null && serialNumber != null) {
        final X500Name issuerX500Name = X500Name.getInstance(issuerName.getEncoded());
        final GeneralName generalName = new GeneralName(issuerX500Name);
        final GeneralNames generalNames = new GeneralNames(generalName);
        IssuerSerial issuerSerial = new IssuerSerial(generalNames, serialNumber);
        return DSSASN1Utils.getDEREncoded(issuerSerial);
	}
	return null;
}
 
Example 8
Source File: Issue166Test.java    From xades4j with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void bcCanCompareCertAndPlainString() throws Exception
{
    X500Name principal1 = X500Name.getInstance(cert.getIssuerX500Principal().getEncoded());
    X500Name principal2 = new X500Name(dnPlain);

    Assert.assertTrue(principal1.equals(principal2));
}
 
Example 9
Source File: Issue166Test.java    From xades4j with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void bcCanCompareCertAndUtf8String() throws Exception
{
    X500Name principal1 = X500Name.getInstance(cert.getIssuerX500Principal().getEncoded());
    X500Name principal2 = new X500Name(dnUtf8);

    Assert.assertTrue(principal1.equals(principal2));
}
 
Example 10
Source File: Issue166Test.java    From xades4j with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void bcCanCompareCertAndPrintableString() throws Exception
{
    X500Name principal1 = X500Name.getInstance(cert.getIssuerX500Principal().getEncoded());
    X500Name principal2 = new X500Name(dnPrintable);

    Assert.assertTrue(principal1.equals(principal2));
}
 
Example 11
Source File: DistinguishedNameComparer.java    From xades4j with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * @exception IllegalArgumentException if the DN string is invalid 
 */
boolean areEqual(X500Principal parsedDn, String stringDn)
{
    X500Name first = X500Name.getInstance(parsedDn.getEncoded());
    X500Name second = X500Name.getInstance(this.x500NameStyle, this.x500NameStyleProvider.fromString(stringDn).getEncoded());
    return first.equals(second);
}
 
Example 12
Source File: SelfCertSignerFactory.java    From athenz with Apache License 2.0 5 votes vote down vote up
@Override
public CertSigner create() {
    
    // extract the private key for this self cert signer
    
    final String pKeyFileName = System.getProperty(ZTSConsts.ZTS_PROP_SELF_SIGNER_PRIVATE_KEY_FNAME);
    final String pKeyPassword = System.getProperty(ZTSConsts.ZTS_PROP_SELF_SIGNER_PRIVATE_KEY_PASSWORD);
    final String csrDn = System.getProperty(ZTSConsts.ZTS_PROP_SELF_SIGNER_CERT_DN,
            "cn=Self Signed Athenz CA,o=Athenz,c=US");

    if (pKeyFileName == null) {
        LOGGER.error("No private key path available for Self Cert Signer Factory");
        return null;
    }
    
    File caKey = new File(pKeyFileName);
    PrivateKey caPrivateKey = Crypto.loadPrivateKey(caKey, pKeyPassword);
    
    // now generate a CSR for our own CA and self sign it
    
    String csr;
    try {
        csr = Crypto.generateX509CSR(caPrivateKey, csrDn, null);
    } catch (IllegalArgumentException | OperatorCreationException | IOException ex) {
        LOGGER.error("Unable to generate X509 CSR for dn: " + csrDn
                + ", error: " + ex.getMessage());
        return null;
    }
    
    // generate our self signed certificate
    
    X500Principal subject = new X500Principal(csrDn);
    X500Name issuer = X500Name.getInstance(subject.getEncoded());
    PKCS10CertificationRequest certReq = Crypto.getPKCS10CertRequest(csr);
    X509Certificate caCertificate = Crypto.generateX509Certificate(certReq,
            caPrivateKey, issuer, 30 * 24 * 60, true);

    return new SelfCertSigner(caPrivateKey, caCertificate);
}
 
Example 13
Source File: OcspRef.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
private String getResponderIdByName() {
   RespID responderId = this.ocsp.getResponderId();
   ResponderID responderIdAsASN1Object = responderId.toASN1Primitive();
   DERTaggedObject derTaggedObject = (DERTaggedObject)responderIdAsASN1Object.toASN1Primitive();
   if (2 == derTaggedObject.getTagNo()) {
      return null;
   } else {
      ASN1Primitive derObject = derTaggedObject.getObject();
      X500Name name = X500Name.getInstance(derObject);
      return RFC2253Parser.normalize(name.toString());
   }
}
 
Example 14
Source File: OcspRef.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
private String getResponderIdByName() {
   RespID responderId = this.ocsp.getResponderId();
   ResponderID responderIdAsASN1Object = responderId.toASN1Primitive();
   DERTaggedObject derTaggedObject = (DERTaggedObject)responderIdAsASN1Object.toASN1Primitive();
   if (2 == derTaggedObject.getTagNo()) {
      return null;
   } else {
      ASN1Primitive derObject = derTaggedObject.getObject();
      X500Name name = X500Name.getInstance(derObject);
      return RFC2253Parser.normalize(name.toString());
   }
}
 
Example 15
Source File: OcspRef.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
private String getResponderIdByName() {
   RespID responderId = this.ocsp.getResponderId();
   ResponderID responderIdAsASN1Object = responderId.toASN1Primitive();
   DERTaggedObject derTaggedObject = (DERTaggedObject)responderIdAsASN1Object.toASN1Primitive();
   if (2 == derTaggedObject.getTagNo()) {
      return null;
   } else {
      ASN1Primitive derObject = derTaggedObject.getObject();
      X500Name name = X500Name.getInstance(derObject);
      return RFC2253Parser.normalize(name.toString());
   }
}
 
Example 16
Source File: BcX500NameDnImpl.java    From java-certificate-authority with Apache License 2.0 4 votes vote down vote up
BcX500NameDnImpl(final X500Principal principal) {
  this.x500Name = X500Name.getInstance(principal.getEncoded());
}
 
Example 17
Source File: CmpAgent.java    From xipki with Apache License 2.0 4 votes vote down vote up
private ProtectionVerificationResult verifyProtection(String tid, GeneralPKIMessage pkiMessage)
    throws CMPException, InvalidKeyException, OperatorCreationException {
  ProtectedPKIMessage protectedMsg = new ProtectedPKIMessage(pkiMessage);

  PKIHeader header = protectedMsg.getHeader();

  if (requestor instanceof Requestor.PbmMacCmpRequestor) {
    if (!protectedMsg.hasPasswordBasedMacProtection()) {
      LOG.warn("NOT_MAC_BASED: {}",
          pkiMessage.getHeader().getProtectionAlg().getAlgorithm().getId());
      return new ProtectionVerificationResult(null, ProtectionResult.SENDER_NOT_AUTHORIZED);
    }

    Responder.PbmMacCmpResponder macResponder = (Responder.PbmMacCmpResponder) responder;
    PBMParameter parameter =
        PBMParameter.getInstance(pkiMessage.getHeader().getProtectionAlg().getParameters());
    AlgorithmIdentifier algId = parameter.getOwf();
    if (!macResponder.isPbmOwfPermitted(algId)) {
      LOG.warn("MAC_ALGO_FORBIDDEN (PBMParameter.owf: {})", algId.getAlgorithm().getId());
      return new ProtectionVerificationResult(null, ProtectionResult.MAC_ALGO_FORBIDDEN);
    }

    algId = parameter.getMac();
    if (!macResponder.isPbmMacPermitted(algId)) {
      LOG.warn("MAC_ALGO_FORBIDDEN (PBMParameter.mac: {})", algId.getAlgorithm().getId());
      return new ProtectionVerificationResult(null, ProtectionResult.MAC_ALGO_FORBIDDEN);
    }

    Requestor.PbmMacCmpRequestor macRequestor = (Requestor.PbmMacCmpRequestor) requestor;
    PKMACBuilder pkMacBuilder = new PKMACBuilder(new JcePKMACValuesCalculator());

    boolean macValid = protectedMsg.verify(pkMacBuilder, macRequestor.getPassword());
    return new ProtectionVerificationResult(requestor,
        macValid ? ProtectionResult.MAC_VALID : ProtectionResult.MAC_INVALID);
  } else {
    if (protectedMsg.hasPasswordBasedMacProtection()) {
      LOG.warn("NOT_SIGNATURE_BASED: {}",
          pkiMessage.getHeader().getProtectionAlg().getAlgorithm().getId());
      return new ProtectionVerificationResult(null, ProtectionResult.SENDER_NOT_AUTHORIZED);
    }

    if (recipientName != null) {
      boolean authorizedResponder = true;
      if (header.getSender().getTagNo() != GeneralName.directoryName) {
        authorizedResponder = false;
      } else {
        X500Name msgSender = X500Name.getInstance(header.getSender().getName());
        authorizedResponder = recipientName.equals(msgSender);
      }

      if (!authorizedResponder) {
        LOG.warn("tid={}: not authorized responder '{}'", tid, header.getSender());
        return new ProtectionVerificationResult(null, ProtectionResult.SENDER_NOT_AUTHORIZED);
      }
    }

    Responder.SignaturetCmpResponder sigResponder =
        (Responder.SignaturetCmpResponder) responder;
    AlgorithmIdentifier protectionAlgo = protectedMsg.getHeader().getProtectionAlg();
    if (!sigResponder.getSigAlgoValidator().isAlgorithmPermitted(protectionAlgo)) {
      String algoName;
      try {
        algoName = AlgorithmUtil.getSignatureAlgoName(protectionAlgo);
      } catch (NoSuchAlgorithmException ex) {
        algoName = protectionAlgo.getAlgorithm().getId();
      }
      LOG.warn("tid={}: response protected by untrusted protection algorithm '{}'",
          tid, algoName);
      return new ProtectionVerificationResult(null, ProtectionResult.SIGNATURE_INVALID);
    }

    X509Cert cert = sigResponder.getCert();
    ContentVerifierProvider verifierProvider = securityFactory.getContentVerifierProvider(cert);
    if (verifierProvider == null) {
      LOG.warn("tid={}: not authorized responder '{}'", tid, header.getSender());
      return new ProtectionVerificationResult(cert, ProtectionResult.SENDER_NOT_AUTHORIZED);
    }

    boolean signatureValid = protectedMsg.verify(verifierProvider);
    return new ProtectionVerificationResult(cert, signatureValid
        ? ProtectionResult.SIGNATURE_VALID : ProtectionResult.SIGNATURE_INVALID);
  }
}
 
Example 18
Source File: ExtensionSyntaxChecker.java    From xipki with Apache License 2.0 4 votes vote down vote up
private static FieldType getFieldType(ASN1Encodable obj) {
  FieldType expectedType;
  if (obj instanceof DERBitString) {
    expectedType = FieldType.BIT_STRING;
  } else if (obj instanceof DERBMPString) {
    expectedType = FieldType.BMPString;
  } else if (obj instanceof ASN1Boolean) {
    expectedType = FieldType.BOOLEAN;
  } else if (obj instanceof ASN1Enumerated) {
    expectedType = FieldType.ENUMERATED;
  } else if (obj instanceof DERGeneralizedTime) {
    expectedType = FieldType.GeneralizedTime;
  } else if (obj instanceof DERIA5String) {
    expectedType = FieldType.IA5String;
  } else if (obj instanceof ASN1Integer) {
    expectedType = FieldType.INTEGER;
  } else if (obj instanceof DERNull) {
    expectedType = FieldType.NULL;
  } else if (obj instanceof DEROctetString) {
    expectedType = FieldType.OCTET_STRING;
  } else if (obj instanceof ASN1ObjectIdentifier) {
    expectedType = FieldType.OID;
  } else if (obj instanceof DERPrintableString) {
    expectedType = FieldType.PrintableString;
  } else if (obj instanceof DERT61String) {
    expectedType = FieldType.TeletexString;
  } else if (obj instanceof DERUTCTime) {
    expectedType = FieldType.UTCTime;
  } else if (obj instanceof DERUTF8String) {
    expectedType = FieldType.UTF8String;
  } else if (obj instanceof X500Name) {
    expectedType = FieldType.Name;
  } else if (obj instanceof ASN1Sequence) {
    try {
      X500Name.getInstance(obj);
      expectedType = FieldType.Name;
    } catch (Exception ex) {
      expectedType = FieldType.SEQUENCE;
    }
  } else if (obj instanceof ASN1Set) {
    expectedType = FieldType.SET;
  } else {
    expectedType = null;
  }

  return expectedType;
}
 
Example 19
Source File: ExtensionSyntaxChecker.java    From xipki with Apache License 2.0 4 votes vote down vote up
private static ASN1Encodable getParsedImplicitValue(String name, ASN1TaggedObject taggedObject,
    FieldType fieldType) throws BadCertTemplateException {
  try {
    switch (fieldType) {
      case BIT_STRING:
        return DERBitString.getInstance(taggedObject, false);
      case BMPString:
        return DERBMPString.getInstance(taggedObject, false);
      case BOOLEAN:
        return ASN1Boolean.getInstance(taggedObject, false);
      case ENUMERATED:
        return ASN1Enumerated.getInstance(taggedObject, false);
      case GeneralizedTime:
        return DERGeneralizedTime.getInstance(taggedObject, false);
      case IA5String:
        return DERIA5String.getInstance(taggedObject, false);
      case INTEGER:
        return ASN1Integer.getInstance(taggedObject, false);
      case Name:
        return X500Name.getInstance(taggedObject, false);
      case NULL:
        if (!(taggedObject.getObject() instanceof ASN1OctetString
            && ((ASN1OctetString) taggedObject.getObject()).getOctets().length == 0)) {
          throw new BadCertTemplateException("invalid " + name);
        }
        return DERNull.INSTANCE;
      case OCTET_STRING:
        return DEROctetString.getInstance(taggedObject, false);
      case OID:
        return ASN1ObjectIdentifier.getInstance(taggedObject, false);
      case PrintableString:
        return DERPrintableString.getInstance(taggedObject, false);
      case RAW:
        return taggedObject.getObject();
      case SEQUENCE:
      case SEQUENCE_OF:
        return ASN1Sequence.getInstance(taggedObject, false);
      case SET:
      case SET_OF:
        return ASN1Set.getInstance(taggedObject, false);
      case TeletexString:
        return DERT61String.getInstance(taggedObject, false);
      case UTCTime:
        return DERUTCTime.getInstance(taggedObject, false);
      case UTF8String:
        return DERUTF8String.getInstance(taggedObject, false);
      default:
        throw new RuntimeException("Unknown FieldType " + fieldType);
    }
  } catch (IllegalArgumentException ex) {
    throw new BadCertTemplateException("invalid " + name, ex);
  }
}
 
Example 20
Source File: X500NameUtils.java    From keystore-explorer with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Convert an X.500 Principal to an X.500 Name.
 *
 * @param principal
 *            X.500 Principal
 * @return X.500 Name
 */
public static X500Name x500PrincipalToX500Name(X500Principal principal) {
	return X500Name.getInstance(KseX500NameStyle.INSTANCE, principal.getEncoded());
}