org.bouncycastle.asn1.DERIA5String Java Examples

The following examples show how to use org.bouncycastle.asn1.DERIA5String. 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: DNetscapeBaseUrl.java    From keystore-explorer with GNU General Public License v3.0 6 votes vote down vote up
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 #2
Source File: XmppDomainVerifier.java    From Conversations with GNU General Public License v3.0 6 votes vote down vote up
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 #3
Source File: SubjectChecker.java    From xipki with 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 #4
Source File: Certprofile.java    From xipki with 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 #5
Source File: XmppDomainVerifier.java    From Pix-Art-Messenger with GNU General Public License v3.0 6 votes vote down vote up
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 #6
Source File: DPolicyQualifierInfoChooser.java    From keystore-explorer with GNU General Public License v3.0 6 votes vote down vote up
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 #7
Source File: DNetscapeCertificateRenewalUrl.java    From keystore-explorer with GNU General Public License v3.0 6 votes vote down vote up
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 #8
Source File: DNetscapeCaPolicyUrl.java    From keystore-explorer with GNU General Public License v3.0 6 votes vote down vote up
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 #9
Source File: DNetscapeCaRevocationUrl.java    From keystore-explorer with GNU General Public License v3.0 6 votes vote down vote up
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 #10
Source File: DNetscapeRevocationUrl.java    From keystore-explorer with GNU General Public License v3.0 6 votes vote down vote up
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 #11
Source File: DNetscapeComment.java    From keystore-explorer with GNU General Public License v3.0 6 votes vote down vote up
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 #12
Source File: DNetscapeSslServerName.java    From keystore-explorer with GNU General Public License v3.0 6 votes vote down vote up
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 #13
Source File: Spkac.java    From keystore-explorer with 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 #14
Source File: PolicyInformationUtil.java    From keystore-explorer with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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 #15
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 #16
Source File: BasicCertificate.java    From signer with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
    * 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 #17
Source File: SubjectAlternativeName.java    From vespa with 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 #18
Source File: XmppDomainVerifier.java    From ComplianceTester with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 #19
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 #20
Source File: InstanceClientRefresh.java    From athenz with 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 #21
Source File: InstanceClientRegister.java    From athenz with 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 #22
Source File: Asn1Dump.java    From keystore-explorer with 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 #23
Source File: Crypto.java    From athenz with 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 #24
Source File: CAdESLevelBaselineB.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
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 #25
Source File: IdSigningPolicy.java    From signer with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 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 #26
Source File: Spkac.java    From keystore-explorer with 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 #27
Source File: CRLCertificateVerifier.java    From oxAuth with 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;
}
 
Example #28
Source File: X509Ext.java    From keystore-explorer with 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 #29
Source File: OCSPCertificateVerifier.java    From oxAuth with MIT License 5 votes vote down vote up
@SuppressWarnings({ "deprecation", "resource" })
private String getOCSPUrl(X509Certificate certificate) throws IOException {
	ASN1Primitive obj;
	try {
		obj = getExtensionValue(certificate, Extension.authorityInfoAccess.getId());
	} catch (IOException ex) {
		log.error("Failed to get OCSP URL", ex);
		return null;
	}

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

	AuthorityInformationAccess authorityInformationAccess = AuthorityInformationAccess.getInstance(obj);

	AccessDescription[] accessDescriptions = authorityInformationAccess.getAccessDescriptions();
	for (AccessDescription accessDescription : accessDescriptions) {
		boolean correctAccessMethod = accessDescription.getAccessMethod().equals(X509ObjectIdentifiers.ocspAccessMethod);
		if (!correctAccessMethod) {
			continue;
		}

		GeneralName name = accessDescription.getAccessLocation();
		if (name.getTagNo() != GeneralName.uniformResourceIdentifier) {
			continue;
		}

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

	return null;

}
 
Example #30
Source File: BasicCertificate.java    From signer with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 
 * @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;
}