Java Code Examples for org.bouncycastle.asn1.DERIA5String

The following examples show how to use org.bouncycastle.asn1.DERIA5String. These examples are extracted from open source projects. 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
/**
    * Returns the AuthorityInfoAccess extension value on list format.<br>
    * Otherwise, returns <b>list empty</b>.<br>
    * @return List Authority info access list
    */
public List<String> getAuthorityInfoAccess() {
	List<String> address = new ArrayList<String>();
	try {
		byte[] authorityInfoAccess = certificate.getExtensionValue(Extension.authorityInfoAccess.getId());
		if (authorityInfoAccess != null && authorityInfoAccess.length > 0) {
			AuthorityInformationAccess infoAccess = AuthorityInformationAccess.getInstance(
					JcaX509ExtensionUtils.parseExtensionValue(authorityInfoAccess));
			for (AccessDescription desc : infoAccess.getAccessDescriptions())
				if (desc.getAccessLocation().getTagNo() == GeneralName.uniformResourceIdentifier)
					address.add(((DERIA5String) desc.getAccessLocation().getName()).getString());
		}
		return address;
	} catch (Exception error) {
		logger.info(error.getMessage());
		return address;
	}
}
 
Example 2
private static OtherName parseOtherName(byte[] otherName) {
    try {
        ASN1Primitive asn1Primitive = ASN1Primitive.fromByteArray(otherName);
        if (asn1Primitive instanceof DERTaggedObject) {
            ASN1Primitive inner = ((DERTaggedObject) asn1Primitive).getObject();
            if (inner instanceof DLSequence) {
                DLSequence sequence = (DLSequence) inner;
                if (sequence.size() >= 2 && sequence.getObjectAt(1) instanceof DERTaggedObject) {
                    String oid = sequence.getObjectAt(0).toString();
                    ASN1Primitive value = ((DERTaggedObject) sequence.getObjectAt(1)).getObject();
                    if (value instanceof DERUTF8String) {
                        return new OtherName(oid, ((DERUTF8String) value).getString());
                    } else if (value instanceof DERIA5String) {
                        return new OtherName(oid, ((DERIA5String) value).getString());
                    }
                }
            }
        }
        return null;
    } catch (IOException e) {
        return null;
    }
}
 
Example 3
Source Project: vespa   Source File: SubjectAlternativeName.java    License: Apache License 2.0 6 votes vote down vote up
private String getValue(GeneralName bcGeneralName) {
    ASN1Encodable name = bcGeneralName.getName();
    switch (bcGeneralName.getTagNo()) {
        case GeneralName.rfc822Name:
        case GeneralName.dNSName:
        case GeneralName.uniformResourceIdentifier:
            return DERIA5String.getInstance(name).getString();
        case GeneralName.directoryName:
            return X500Name.getInstance(name).toString();
        case GeneralName.iPAddress:
            byte[] octets = DEROctetString.getInstance(name.toASN1Primitive()).getOctets();
            try {
                return InetAddress.getByAddress(octets).getHostAddress();
            } catch (UnknownHostException e) {
                // Only thrown if IP address is of invalid length, which is an illegal argument
                throw new IllegalArgumentException(e);
            }
        default:
            return name.toString();
    }
}
 
Example 4
Source Project: athenz   Source File: CryptoTest.java    License: 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 5
Source Project: athenz   Source File: CryptoTest.java    License: 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 6
/**
 * Get string representation of policy qualifier info.
 *
 * @param policyQualifierInfo
 *            Policy qualifier info
 * @return String representation of policy qualifier info
 * @throws IOException
 *             If policy qualifier info is invalid
 */
public static String toString(PolicyQualifierInfo policyQualifierInfo) throws IOException {
	StringBuffer sbPolicyQualifier = new StringBuffer();

	ASN1ObjectIdentifier policyQualifierId = policyQualifierInfo.getPolicyQualifierId();

	CertificatePolicyQualifierType certificatePolicyQualifierType = CertificatePolicyQualifierType
			.resolveOid(policyQualifierId.getId());

	if (certificatePolicyQualifierType == PKIX_CPS_POINTER_QUALIFIER) {
		DERIA5String cpsPointer = ((DERIA5String) policyQualifierInfo.getQualifier());

		sbPolicyQualifier
		.append(MessageFormat.format(res.getString("PolicyInformationUtil.CpsPointer"), cpsPointer));
	} else if (certificatePolicyQualifierType == PKIX_USER_NOTICE_QUALIFIER) {
		ASN1Encodable userNoticeObj = policyQualifierInfo.getQualifier();

		UserNotice userNotice = UserNotice.getInstance(userNoticeObj);

		sbPolicyQualifier.append(MessageFormat.format(res.getString("PolicyInformationUtil.UserNotice"),
				toString(userNotice)));
	}

	return sbPolicyQualifier.toString();
}
 
Example 7
Source Project: keystore-explorer   Source File: Spkac.java    License: GNU General Public License v3.0 6 votes vote down vote up
private ASN1Sequence createPublicKeyAndChallenge() throws SpkacException {
	ASN1EncodableVector publicKeyAlgorithm = new ASN1EncodableVector();
	publicKeyAlgorithm.add(new ASN1ObjectIdentifier(getPublicKeyAlg().oid()));

	if (getPublicKey() instanceof RSAPublicKey) {
		publicKeyAlgorithm.add(DERNull.INSTANCE);
	} else {
		DSAParams dsaParams = ((DSAPublicKey) getPublicKey()).getParams();

		ASN1EncodableVector dssParams = new ASN1EncodableVector();
		dssParams.add(new ASN1Integer(dsaParams.getP()));
		dssParams.add(new ASN1Integer(dsaParams.getQ()));
		dssParams.add(new ASN1Integer(dsaParams.getG()));

		publicKeyAlgorithm.add(new DERSequence(dssParams));
	}

	ASN1EncodableVector spki = new ASN1EncodableVector();
	spki.add(new DERSequence(publicKeyAlgorithm));
	spki.add(encodePublicKeyAsBitString(getPublicKey()));

	ASN1EncodableVector publicKeyAndChallenge = new ASN1EncodableVector();
	publicKeyAndChallenge.add(new DERSequence(spki));
	publicKeyAndChallenge.add(new DERIA5String(getChallenge()));
	return new DERSequence(publicKeyAndChallenge);
}
 
Example 8
private void okPressed() {
	String netscapeBaseUrlStr = jtfNetscapeBaseUrl.getText().trim();

	if (netscapeBaseUrlStr.length() == 0) {
		JOptionPane.showMessageDialog(this, res.getString("DNetscapeBaseUrl.ValueReq.message"), getTitle(),
				JOptionPane.WARNING_MESSAGE);
		return;
	}

	DERIA5String netscapeBaseUrl = new DERIA5String(netscapeBaseUrlStr);

	try {
		value = netscapeBaseUrl.getEncoded(ASN1Encoding.DER);
	} catch (IOException e) {
		DError.displayError(this, e);
		return;
	}

	closeDialog();
}
 
Example 9
private void okPressed() {
	String netscapeSslServerNameStr = jtfNetscapeSslServerName.getText().trim();

	if (netscapeSslServerNameStr.length() == 0) {
		JOptionPane.showMessageDialog(this, res.getString("DNetscapeSslServerName.ValueReq.message"), getTitle(),
				JOptionPane.WARNING_MESSAGE);
		return;
	}

	DERIA5String netscapeSslServerName = new DERIA5String(netscapeSslServerNameStr);

	try {
		value = netscapeSslServerName.getEncoded(ASN1Encoding.DER);
	} catch (IOException e) {
		DError.displayError(this, e);
		return;
	}

	closeDialog();
}
 
Example 10
private void okPressed() {
	String netscapeCommentStr = jtaNetscapeComment.getText().trim();

	if (netscapeCommentStr.length() == 0) {
		JOptionPane.showMessageDialog(this, res.getString("DNetscapeComment.ValueReq.message"), getTitle(),
				JOptionPane.WARNING_MESSAGE);
		return;
	}

	DERIA5String netscapeComment = new DERIA5String(netscapeCommentStr);

	try {
		value = netscapeComment.getEncoded(ASN1Encoding.DER);
	} catch (IOException e) {
		DError.displayError(this, e);
		return;
	}

	closeDialog();
}
 
Example 11
private void okPressed() {
	String netscapeRevocationUrlStr = jtfNetscapeRevocationUrl.getText().trim();

	if (netscapeRevocationUrlStr.length() == 0) {
		JOptionPane.showMessageDialog(this, res.getString("DNetscapeRevocationUrl.ValueReq.message"), getTitle(),
				JOptionPane.WARNING_MESSAGE);
		return;
	}

	DERIA5String netscapeRevocationUrl = new DERIA5String(netscapeRevocationUrlStr);

	try {
		value = netscapeRevocationUrl.getEncoded(ASN1Encoding.DER);
	} catch (IOException e) {
		DError.displayError(this, e);
		return;
	}

	closeDialog();
}
 
Example 12
private void okPressed() {
	String netscapeCaRevocationUrlStr = jtfNetscapeCaRevocationUrl.getText().trim();

	if (netscapeCaRevocationUrlStr.length() == 0) {
		JOptionPane.showMessageDialog(this, res.getString("DNetscapeCaRevocationUrl.ValueReq.message"), getTitle(),
				JOptionPane.WARNING_MESSAGE);
		return;
	}

	DERIA5String netscapeCaRevocationUrl = new DERIA5String(netscapeCaRevocationUrlStr);

	try {
		value = netscapeCaRevocationUrl.getEncoded(ASN1Encoding.DER);
	} catch (IOException e) {
		DError.displayError(this, e);
		return;
	}

	closeDialog();
}
 
Example 13
private void okPressed() {
	String netscapeCaPolicyUrlStr = jtfNetscapeCaPolicyUrl.getText().trim();

	if (netscapeCaPolicyUrlStr.length() == 0) {
		JOptionPane.showMessageDialog(this, res.getString("DNetscapeCaPolicyUrl.ValueReq.message"), getTitle(),
				JOptionPane.WARNING_MESSAGE);
		return;
	}

	DERIA5String netscapeCaPolicyUrl = new DERIA5String(netscapeCaPolicyUrlStr);

	try {
		value = netscapeCaPolicyUrl.getEncoded(ASN1Encoding.DER);
	} catch (IOException e) {
		DError.displayError(this, e);
		return;
	}

	closeDialog();
}
 
Example 14
private void okPressed() {
	String netscapeCertificateRenewalUrlStr = jtfNetscapeCertificateRenewalUrl.getText().trim();

	if (netscapeCertificateRenewalUrlStr.length() == 0) {
		JOptionPane.showMessageDialog(this, res.getString("DNetscapeCertificateRenewalUrl.ValueReq.message"),
				getTitle(), JOptionPane.WARNING_MESSAGE);
		return;
	}

	DERIA5String netscapeCertificateRenewalUrl = new DERIA5String(netscapeCertificateRenewalUrlStr);

	try {
		value = netscapeCertificateRenewalUrl.getEncoded(ASN1Encoding.DER);
	} catch (IOException e) {
		DError.displayError(this, e);
		return;
	}

	closeDialog();
}
 
Example 15
private void populate(PolicyQualifierInfo policyQualifierInfo) throws IOException {
	if (policyQualifierInfo == null) {
		jrbCps.setSelected(true);
	} else {
		ASN1ObjectIdentifier policyQualifierId = policyQualifierInfo.getPolicyQualifierId();

		if (policyQualifierId.equals(new ASN1ObjectIdentifier(PKIX_CPS_POINTER_QUALIFIER.oid()))) {
			jrbCps.setSelected(true);
			jtfCps.setText(((DERIA5String) policyQualifierInfo.getQualifier()).getString());
			jtfCps.setCaretPosition(0);
		} else if (policyQualifierId.equals(new ASN1ObjectIdentifier(PKIX_USER_NOTICE_QUALIFIER.oid()))) {
			jrbUserNotice.setSelected(true);

			ASN1Encodable userNoticeObj = policyQualifierInfo.getQualifier();

			UserNotice userNotice = UserNotice.getInstance(userNoticeObj);

			junUserNotice.setUserNotice(userNotice);
		} else {
			jrbCps.setSelected(true);
		}
	}
}
 
Example 16
private static Pair<String, String> parseOtherName(byte[] otherName) {
    try {
        ASN1Primitive asn1Primitive = ASN1Primitive.fromByteArray(otherName);
        if (asn1Primitive instanceof DERTaggedObject) {
            ASN1Primitive inner = ((DERTaggedObject) asn1Primitive).getObject();
            if (inner instanceof DLSequence) {
                DLSequence sequence = (DLSequence) inner;
                if (sequence.size() >= 2 && sequence.getObjectAt(1) instanceof DERTaggedObject) {
                    String oid = sequence.getObjectAt(0).toString();
                    ASN1Primitive value = ((DERTaggedObject) sequence.getObjectAt(1)).getObject();
                    if (value instanceof DERUTF8String) {
                        return new Pair<>(oid, ((DERUTF8String) value).getString());
                    } else if (value instanceof DERIA5String) {
                        return new Pair<>(oid, ((DERIA5String) value).getString());
                    }
                }
            }
        }
        return null;
    } catch (IOException e) {
        return null;
    }
}
 
Example 17
Source Project: xipki   Source File: Certprofile.java    License: Apache License 2.0 6 votes vote down vote up
public ASN1Encodable createString(String text) {
  Args.notNull(text, "text");

  if (teletexString == this) {
    return new DERT61String(text);
  } else if (printableString == this) {
    return new DERPrintableString(text);
  } else if (utf8String == this) {
    return new DERUTF8String(text);
  } else if (bmpString == this) {
    return new DERBMPString(text);
  } else if (ia5String == this) {
    return new DERIA5String(text, true);
  } else {
    throw new IllegalStateException("should not reach here, unknown StringType " + this.name());
  }
}
 
Example 18
Source Project: xipki   Source File: SubjectChecker.java    License: Apache License 2.0 6 votes vote down vote up
private static boolean matchStringType(ASN1Encodable atvValue, StringType stringType) {
  boolean correctStringType = true;
  switch (stringType) {
    case bmpString:
      correctStringType = (atvValue instanceof DERBMPString);
      break;
    case printableString:
      correctStringType = (atvValue instanceof DERPrintableString);
      break;
    case teletexString:
      correctStringType = (atvValue instanceof DERT61String);
      break;
    case utf8String:
      correctStringType = (atvValue instanceof DERUTF8String);
      break;
    case ia5String:
      correctStringType = (atvValue instanceof DERIA5String);
      break;
    default:
      throw new IllegalStateException("should not reach here, unknown StringType " + stringType);
  } // end switch
  return correctStringType;
}
 
Example 19
private static Pair<String, String> parseOtherName(byte[] otherName) {
    try {
        ASN1Primitive asn1Primitive = ASN1Primitive.fromByteArray(otherName);
        if (asn1Primitive instanceof DERTaggedObject) {
            ASN1Primitive inner = ((DERTaggedObject) asn1Primitive).getObject();
            if (inner instanceof DLSequence) {
                DLSequence sequence = (DLSequence) inner;
                if (sequence.size() >= 2 && sequence.getObjectAt(1) instanceof DERTaggedObject) {
                    String oid = sequence.getObjectAt(0).toString();
                    ASN1Primitive value = ((DERTaggedObject) sequence.getObjectAt(1)).getObject();
                    if (value instanceof DERUTF8String) {
                        return new Pair<>(oid, ((DERUTF8String) value).getString());
                    } else if (value instanceof DERIA5String) {
                        return new Pair<>(oid, ((DERIA5String) value).getString());
                    }
                }
            }
        }
        return null;
    } catch (IOException e) {
        return null;
    }
}
 
Example 20
/**
 * org.bouncycastle.asn1.ASN1ObjectIdentifier sigPolicyId
 * org.bouncycastle.asn1.esf.OtherHashAlgAndValue sigPolicyHash
 * List&lt;org.bouncycastle.asn1.esf.SigPolicyQualifierInfo&gt; sigPolicyQualifierInfos
 */
@Override
public Attribute getValue() {

  //Atributo 1
    ASN1ObjectIdentifier sigPolicyId = new ASN1ObjectIdentifier(signaturePolicy.getSignPolicyInfo().getSignPolicyIdentifier().getValue());

    //Atributo 2
    OtherHashAlgAndValue sigPolicyHash = new OtherHashAlgAndValue(new AlgorithmIdentifier(
    		new ASN1ObjectIdentifier(signaturePolicy.getSignPolicyHashAlg().getAlgorithm().getValue())), 
    		signaturePolicy.getSignPolicyHash().getDerOctetString());

    //Atributo 3
    List<SigPolicyQualifierInfo> sigPolicyQualifierInfos = new ArrayList<SigPolicyQualifierInfo>();

    ASN1ObjectIdentifier sigPolicyQualifierId = new ASN1ObjectIdentifier("1.2.840.113549.1.9.16.5.1");
    DERIA5String sigQualifier = new DERIA5String(signaturePolicy.getSignPolicyURI());
    SigPolicyQualifierInfo bcSigPolicyQualifierInfo = new SigPolicyQualifierInfo(sigPolicyQualifierId, sigQualifier);
    sigPolicyQualifierInfos.add(bcSigPolicyQualifierInfo);

    SigPolicyQualifiers sigPolicyQualifiers = new SigPolicyQualifiers(sigPolicyQualifierInfos.toArray(new SigPolicyQualifierInfo[]{}));

    SignaturePolicyId signaturePolicyId = new SignaturePolicyId(sigPolicyId, sigPolicyHash, sigPolicyQualifiers);
    return new Attribute(new ASN1ObjectIdentifier(oid), new DERSet(signaturePolicyId));
    
    
}
 
Example 21
Source Project: signer   Source File: PolicyInfo.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void parse(ASN1Primitive primitive) {
    ASN1Sequence sequence1 = ASN1Object.getDERSequence(primitive);
    this.signingPeriod = new SigningPeriod();
    this.signingPeriod.parse(sequence1.getObjectAt(0).toASN1Primitive());
    int indice = 2;

    ASN1Primitive secondObject = sequence1.getObjectAt(1).toASN1Primitive();
    if (secondObject instanceof ASN1ObjectIdentifier) {
        indice = 1;
    }
    if (indice == 2) {
        this.revocationDate = new GeneralizedTime();
        this.revocationDate.parse(secondObject);
    }
    this.policyOID = new ObjectIdentifier();
    this.policyOID.parse(sequence1.getObjectAt(indice).toASN1Primitive());
    DERIA5String policyURI = (DERIA5String) sequence1.getObjectAt(indice + 1);
    this.policyURI = policyURI.getString();

    ASN1Primitive policyDigest = sequence1.getObjectAt(indice + 2).toASN1Primitive();
    ASN1Sequence sequence2 = ASN1Sequence.getInstance(policyDigest);

    DEROctetString derOctetString = (DEROctetString) sequence2.getObjectAt(1).toASN1Primitive();
    ASN1Sequence sequence3 = ASN1Object.getDERSequence(sequence2.getObjectAt(0).toASN1Primitive());
    ASN1ObjectIdentifier objectIdentifier = (ASN1ObjectIdentifier) sequence3.getObjectAt(0).toASN1Primitive();
    AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(objectIdentifier);
    this.policyDigest = new OtherHashAlgAndValue(algorithmIdentifier, derOctetString);
}
 
Example 22
/**
 * 
 * @return A list of ulrs that inform the location of the certificate revocation lists
 * @throws IOException exception
 */
public List<String> getCRLDistributionPoint() throws IOException {

    List<String> crlUrls = new ArrayList<>();
    ASN1Primitive primitive = getExtensionValue(Extension.cRLDistributionPoints.getId());
    if (primitive == null) {
        return null;
    }
    CRLDistPoint crlDistPoint = CRLDistPoint.getInstance(primitive);
    DistributionPoint[] distributionPoints = crlDistPoint.getDistributionPoints();

    for (DistributionPoint distributionPoint : distributionPoints) {
        DistributionPointName dpn = distributionPoint.getDistributionPoint();
        // Look for URIs in fullName
        if (dpn != null) {
            if (dpn.getType() == DistributionPointName.FULL_NAME) {
                GeneralName[] genNames = GeneralNames.getInstance(dpn.getName()).getNames();
                for (GeneralName genName : genNames) {
                    if (genName.getTagNo() == GeneralName.uniformResourceIdentifier) {
                        String url = DERIA5String.getInstance(genName.getName()).getString();
                        crlUrls.add(url);
                        logger.info("Adicionando a url {}", url);
                    }
                }
            }
        }
    }
    return crlUrls;
}
 
Example 23
Source Project: athenz   Source File: InstanceClientRegister.java    License: Apache License 2.0 5 votes vote down vote up
public static String generateCSR(String domainName, String serviceName,
        String instanceId, String dnsSuffix, PrivateKey key) {
    
    final String dn = "cn=" + domainName + "." + serviceName + ",o=Athenz";
    
    // now let's generate our dsnName field based on our principal's details
    
    StringBuilder dnsName = new StringBuilder(128);
    dnsName.append(serviceName);
    dnsName.append('.');
    dnsName.append(domainName.replace('.', '-'));
    dnsName.append('.');
    dnsName.append(dnsSuffix);
    
    GeneralName[] sanArray = new GeneralName[2];
    sanArray[0] = new GeneralName(GeneralName.dNSName, new DERIA5String(dnsName.toString()));
    
    // next we include our instance id
    
    StringBuilder dnsInstance = new StringBuilder(128);
    dnsInstance.append(instanceId);
    dnsInstance.append(".instanceid.athenz.");
    dnsInstance.append(dnsSuffix);
    
    sanArray[1] = new GeneralName(GeneralName.dNSName, new DERIA5String(dnsInstance.toString()));
    
    String csr = null;
    try {
        csr = Crypto.generateX509CSR(key, dn, sanArray);
    } catch (OperatorCreationException | IOException ex) {
        System.err.println(ex.getMessage());
    }
    
    return csr;
}
 
Example 24
Source Project: athenz   Source File: InstanceClientRefresh.java    License: Apache License 2.0 5 votes vote down vote up
public static String generateCSR(String domainName, String serviceName,
        String instanceId, String dnsSuffix, PrivateKey key) {
    
    final String dn = "cn=" + domainName + "." + serviceName + ",o=Athenz";
    
    // now let's generate our dsnName field based on our principal's details
    
    StringBuilder dnsName = new StringBuilder(128);
    dnsName.append(serviceName);
    dnsName.append('.');
    dnsName.append(domainName.replace('.', '-'));
    dnsName.append('.');
    dnsName.append(dnsSuffix);
    
    GeneralName[] sanArray = new GeneralName[2];
    sanArray[0] = new GeneralName(GeneralName.dNSName, new DERIA5String(dnsName.toString()));
    
    // next we include our instance id
    
    StringBuilder dnsInstance = new StringBuilder(128);
    dnsInstance.append(instanceId);
    dnsInstance.append(".instanceid.athenz.");
    dnsInstance.append(dnsSuffix);
    
    sanArray[1] = new GeneralName(GeneralName.dNSName, new DERIA5String(dnsInstance.toString()));
    
    String csr = null;
    try {
        csr = Crypto.generateX509CSR(key, dn, sanArray);
    } catch (OperatorCreationException | IOException ex) {
        System.err.println(ex.getMessage());
    }
    
    return csr;
}
 
Example 25
Source Project: athenz   Source File: Crypto.java    License: Apache License 2.0 5 votes vote down vote up
private static List<String> extractX509CSRSANField(PKCS10CertificationRequest certReq, int tagNo) {

        List<String> values = new ArrayList<>();
        Attribute[] attributes = certReq.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
        for (Attribute attribute : attributes) {
            for (ASN1Encodable value : attribute.getAttributeValues()) {
                Extensions extensions = Extensions.getInstance(value);
                GeneralNames gns = GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName);
                ///CLOVER:OFF
                if (gns == null) {
                    continue;
                }
                ///CLOVER:ON
                for (GeneralName name : gns.getNames()) {

                    // GeneralName ::= CHOICE {
                    //     otherName                       [0]     OtherName,
                    //     rfc822Name                      [1]     IA5String,
                    //     dNSName                         [2]     IA5String,
                    //     x400Address                     [3]     ORAddress,
                    //     directoryName                   [4]     Name,
                    //     ediPartyName                    [5]     EDIPartyName,
                    //     uniformResourceIdentifier       [6]     IA5String,
                    //     iPAddress                       [7]     OCTET STRING,
                    //     registeredID                    [8]     OBJECT IDENTIFIER}

                    if (name.getTagNo() == tagNo) {
                        values.add(((DERIA5String) name.getName()).getString());
                    }
                }
            }
        }
        return values;
    }
 
Example 26
Source Project: keystore-explorer   Source File: X509Ext.java    License: GNU General Public License v3.0 5 votes vote down vote up
private String getAttributeValueString(ASN1ObjectIdentifier attributeType, ASN1Encodable attributeValue)
		throws IOException {

	/* AttributeValue ::= ANY  */

	// Get value string for recognized attribute types
	AttributeTypeType attributeTypeType = AttributeTypeType.resolveOid(attributeType.getId());

	switch (attributeTypeType) {
	case DATE_OF_BIRTH:
		return getGeneralizedTimeString(ASN1GeneralizedTime.getInstance(attributeValue));
	case SERIAL_NUMBER:
	case UNSTRUCTURED_ADDRESS:
	case COUNTRY_NAME:
	case GENDER:
	case COUNTRY_OF_CITIZENSHIP:
	case COUNTRY_OF_RESIDENCE:
		return DERPrintableString.getInstance(attributeValue).getString();
	case COMMON_NAME:
	case LOCALITY_NAME:
	case STATE_NAME:
	case STREET_ADDRESS:
	case ORGANIZATION_NAME:
	case ORGANIZATIONAL_UNIT:
	case TITLE:
	case USER_ID:
	case PLACE_OF_BIRTH:
		return DirectoryString.getInstance(attributeValue).getString();
	case MAIL:
	case EMAIL_ADDRESS:
	case UNSTRUCTURED_NAME:
	case DOMAIN_COMPONENT:
		return DERIA5String.getInstance(attributeValue).getString();
	default:
		// Attribute type not recognized - return hex string for value
		return HexUtil.getHexString(attributeValue.toASN1Primitive().getEncoded());
	}
}
 
Example 27
Source Project: keystore-explorer   Source File: Spkac.java    License: GNU General Public License v3.0 5 votes vote down vote up
private void decodeSpkac(byte[] der) throws SpkacException {
	try {
		ASN1Sequence signedPublicKeyAndChallenge = ASN1Sequence.getInstance(der);

		ASN1Sequence publicKeyAndChallenge = (ASN1Sequence) signedPublicKeyAndChallenge.getObjectAt(0);
		ASN1Sequence signatureAlgorithm = (ASN1Sequence) signedPublicKeyAndChallenge.getObjectAt(1);
		DERBitString signature = (DERBitString) signedPublicKeyAndChallenge.getObjectAt(2);

		ASN1ObjectIdentifier signatureAlgorithmOid = (ASN1ObjectIdentifier) signatureAlgorithm.getObjectAt(0);

		ASN1Sequence spki = (ASN1Sequence) publicKeyAndChallenge.getObjectAt(0);
		DERIA5String challenge = (DERIA5String) publicKeyAndChallenge.getObjectAt(1);

		ASN1Sequence publicKeyAlgorithm = (ASN1Sequence) spki.getObjectAt(0);
		DERBitString publicKey = (DERBitString) spki.getObjectAt(1);

		ASN1ObjectIdentifier publicKeyAlgorithmOid = (ASN1ObjectIdentifier) publicKeyAlgorithm.getObjectAt(0);
		ASN1Primitive algorithmParameters = publicKeyAlgorithm.getObjectAt(1).toASN1Primitive();

		this.challenge = challenge.getString();
		this.publicKey = decodePublicKeyFromBitString(publicKeyAlgorithmOid, algorithmParameters, publicKey);
		this.signatureAlgorithm = getSignatureAlgorithm(signatureAlgorithmOid);
		this.signature = signature.getBytes();
	} catch (Exception ex) {
		throw new SpkacException(res.getString("NoDecodeSpkac.exception.message"), ex);
	}
}
 
Example 28
Source Project: keystore-explorer   Source File: Asn1Dump.java    License: GNU General Public License v3.0 5 votes vote down vote up
private String dumpString(ASN1String asn1String) {
	StringBuilder sb = new StringBuilder();

	sb.append(indentSequence.toString(indentLevel));

	if (asn1String instanceof DERBMPString) {
		sb.append("BMP STRING=");
	} else if (asn1String instanceof DERGeneralString) {
		sb.append("GENERAL STRING=");
	} else if (asn1String instanceof DERIA5String) {
		sb.append("IA5 STRING=");
	} else if (asn1String instanceof DERNumericString) {
		sb.append("NUMERIC STRING=");
	} else if (asn1String instanceof DERPrintableString) {
		sb.append("PRINTABLE STRING=");
	} else if (asn1String instanceof DERT61String) {
		sb.append("TELETEX STRING=");
	} else if (asn1String instanceof DERUniversalString) {
		sb.append("UNIVERSAL STRING=");
	} else if (asn1String instanceof DERUTF8String) {
		sb.append("UTF8 STRING=");
	} else if (asn1String instanceof DERVisibleString) {
		sb.append("VISIBLE STRING=");
	} else {
		sb.append("UNKNOWN STRING=");
	}

	sb.append("'");
	sb.append(asn1String.getString());
	sb.append("'");
	sb.append(NEWLINE);

	return sb.toString();
}
 
Example 29
private void addSignaturePolicyId(final CAdESSignatureParameters parameters, final ASN1EncodableVector signedAttributes) {

		Policy policy = parameters.bLevel().getSignaturePolicy();
		if (policy != null) {

			final String policyId = policy.getId();
			SignaturePolicyIdentifier sigPolicy = null;

			if (Utils.isStringEmpty(policyId)) {// implicit
				sigPolicy = new SignaturePolicyIdentifier();
			} else { // explicit
				final ASN1ObjectIdentifier derOIPolicyId = new ASN1ObjectIdentifier(policyId);
				final ASN1ObjectIdentifier oid = new ASN1ObjectIdentifier(policy.getDigestAlgorithm().getOid());
				final AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(oid);
				OtherHashAlgAndValue otherHashAlgAndValue = new OtherHashAlgAndValue(algorithmIdentifier, new DEROctetString(policy.getDigestValue()));

				if (Utils.isStringNotEmpty(policy.getSpuri())) {
					SigPolicyQualifierInfo policyQualifierInfo = new SigPolicyQualifierInfo(PKCSObjectIdentifiers.id_spq_ets_uri,
							new DERIA5String(policy.getSpuri()));
					SigPolicyQualifierInfo[] qualifierInfos = new SigPolicyQualifierInfo[] { policyQualifierInfo };
					SigPolicyQualifiers qualifiers = new SigPolicyQualifiers(qualifierInfos);

					sigPolicy = new SignaturePolicyIdentifier(new SignaturePolicyId(derOIPolicyId, otherHashAlgAndValue, qualifiers));
				} else {
					sigPolicy = new SignaturePolicyIdentifier(new SignaturePolicyId(derOIPolicyId, otherHashAlgAndValue));
				}
			}

			final DERSet attrValues = new DERSet(sigPolicy);
			final Attribute attribute = new Attribute(id_aa_ets_sigPolicyId, attrValues);
			signedAttributes.add(attribute);
		}
	}
 
Example 30
Source Project: oxAuth   Source File: CRLCertificateVerifier.java    License: MIT License 5 votes vote down vote up
public String getCrlUri(X509Certificate certificate) throws IOException {
	ASN1Primitive obj;
	try {
		obj = getExtensionValue(certificate, Extension.cRLDistributionPoints.getId());
	} catch (IOException ex) {
		log.error("Failed to get CRL URL", ex);
		return null;
	}

	if (obj == null) {
		return null;
	}

	CRLDistPoint distPoint = CRLDistPoint.getInstance(obj);

	DistributionPoint[] distributionPoints = distPoint.getDistributionPoints();
	for (DistributionPoint distributionPoint : distributionPoints) {
		DistributionPointName distributionPointName = distributionPoint.getDistributionPoint();
		if (DistributionPointName.FULL_NAME != distributionPointName.getType()) {
			continue;
		}

		GeneralNames generalNames = (GeneralNames) distributionPointName.getName();
		GeneralName[] names = generalNames.getNames();
		for (GeneralName name : names) {
			if (name.getTagNo() != GeneralName.uniformResourceIdentifier) {
				continue;
			}

			DERIA5String derStr = DERIA5String.getInstance((ASN1TaggedObject) name.toASN1Primitive(), false);
			return derStr.getString();
		}
	}

	return null;
}