Java源码示例:org.bouncycastle.asn1.x500.AttributeTypeAndValue
示例1
public RdnPanelList(X500Name x500Name, boolean editable) {
setLayout(new MigLayout("insets dialog, flowy", "[right]", "[]rel[]"));
// we have to reverse RDN order for dialog
List<RDN> rdnsAsList = Arrays.asList(x500Name.getRDNs());
Collections.reverse(rdnsAsList);
for (RDN rdn : rdnsAsList) {
this.editable = editable;
for (AttributeTypeAndValue atav : rdn.getTypesAndValues()) {
String type = OidDisplayNameMapping.getDisplayNameForOid(atav.getType().getId());
String value = atav.getValue().toString();
addItem(new RdnPanel(new JComboBox<Object>(comboBoxEntries), type, value, this, editable));
}
}
}
示例2
public static String getCommonName(X500Name name) {
Args.notNull(name, "name");
RDN[] rdns = name.getRDNs(ObjectIdentifiers.DN.CN);
if (rdns != null && rdns.length > 0) {
RDN rdn = rdns[0];
AttributeTypeAndValue atv = null;
if (rdn.isMultiValued()) {
for (AttributeTypeAndValue m : rdn.getTypesAndValues()) {
if (m.getType().equals(ObjectIdentifiers.DN.CN)) {
atv = m;
break;
}
}
} else {
atv = rdn.getFirst();
}
return (atv == null) ? null : rdnValueToString(atv.getValue());
}
return null;
}
示例3
/**
* Reorders DN to the order the elements appear in the RFC 2253 table
*
* https://www.ietf.org/rfc/rfc2253.txt
*
* String X.500 AttributeType
* ------------------------------
* CN commonName
* L localityName
* ST stateOrProvinceName
* O organizationName
* OU organizationalUnitName
* C countryName
* STREET streetAddress
* DC domainComponent
* UID userid
*
* @param dn a possibly unordered DN
* @return the ordered dn
*/
public static String reorderDn(String dn) {
RDN[] rdNs = new X500Name(dn).getRDNs();
Arrays.sort(rdNs, new Comparator<RDN>() {
@Override
public int compare(RDN o1, RDN o2) {
AttributeTypeAndValue o1First = o1.getFirst();
AttributeTypeAndValue o2First = o2.getFirst();
ASN1ObjectIdentifier o1Type = o1First.getType();
ASN1ObjectIdentifier o2Type = o2First.getType();
Integer o1Rank = dnOrderMap.get(o1Type);
Integer o2Rank = dnOrderMap.get(o2Type);
if (o1Rank == null) {
if (o2Rank == null) {
int idComparison = o1Type.getId().compareTo(o2Type.getId());
if (idComparison != 0) {
return idComparison;
}
return String.valueOf(o1Type).compareTo(String.valueOf(o2Type));
}
return 1;
} else if (o2Rank == null) {
return -1;
}
return o1Rank - o2Rank;
}
});
return new X500Name(rdNs).toString();
}
示例4
/**
* Reorders DN to the order the elements appear in the RFC 2253 table
*
* https://www.ietf.org/rfc/rfc2253.txt
*
* String X.500 AttributeType
* ------------------------------
* CN commonName
* L localityName
* ST stateOrProvinceName
* O organizationName
* OU organizationalUnitName
* C countryName
* STREET streetAddress
* DC domainComponent
* UID userid
*
* @param dn a possibly unordered DN
* @return the ordered dn
*/
public static String reorderDn(String dn) {
RDN[] rdNs = new X500Name(dn).getRDNs();
Arrays.sort(rdNs, new Comparator<RDN>() {
@Override
public int compare(RDN o1, RDN o2) {
AttributeTypeAndValue o1First = o1.getFirst();
AttributeTypeAndValue o2First = o2.getFirst();
ASN1ObjectIdentifier o1Type = o1First.getType();
ASN1ObjectIdentifier o2Type = o2First.getType();
Integer o1Rank = dnOrderMap.get(o1Type);
Integer o2Rank = dnOrderMap.get(o2Type);
if (o1Rank == null) {
if (o2Rank == null) {
int idComparison = o1Type.getId().compareTo(o2Type.getId());
if (idComparison != 0) {
return idComparison;
}
return String.valueOf(o1Type).compareTo(String.valueOf(o2Type));
}
return 1;
} else if (o2Rank == null) {
return -1;
}
return o1Rank - o2Rank;
}
});
return new X500Name(rdNs).toString();
}
示例5
@Override
public String toString(X500Name name) {
// Convert in reverse
StringBuffer buf = new StringBuffer();
boolean first = true;
RDN[] rdns = name.getRDNs();
for (int i = rdns.length - 1; i >= 0; i--) {
if (first) {
first = false;
} else {
buf.append(',');
}
if (rdns[i].isMultiValued()) {
AttributeTypeAndValue[] atv = rdns[i].getTypesAndValues();
boolean firstAtv = true;
for (int j = 0; j != atv.length; j++) {
if (firstAtv) {
firstAtv = false;
} else {
buf.append('+');
}
IETFUtils.appendTypeAndValue(buf, atv[j], DEFAULT_SYMBOLS);
}
} else {
IETFUtils.appendTypeAndValue(buf, rdns[i].getFirst(), DEFAULT_SYMBOLS);
}
}
return buf.toString();
}
示例6
/**
* Return CN of a X.500 name
*
* @param name X.500 name object
* @return CN from Name or an empty string if no CN found
*/
public static String extractCN(X500Name name) {
for (RDN rdn : name.getRDNs()) {
AttributeTypeAndValue atav = rdn.getFirst();
if (atav.getType().equals(BCStyle.CN)) {
return atav.getValue().toString();
}
}
return "";
}
示例7
public List<RDN> getRdns(boolean noEmptyRdns) {
List<RDN> rdns = new ArrayList<>();
for (RdnPanel rdnPanel : entries) {
ASN1ObjectIdentifier attrType = OidDisplayNameMapping.getOidForDisplayName(rdnPanel.getAttributeName());
if (noEmptyRdns && StringUtils.trimAndConvertEmptyToNull(rdnPanel.getAttributeValue()) == null) {
continue;
}
ASN1Encodable attrValue = KseX500NameStyle.INSTANCE.stringToValue(attrType, rdnPanel.getAttributeValue());
rdns.add(new RDN(new AttributeTypeAndValue(attrType, attrValue)));
}
return rdns;
}
示例8
/**
* Reorders DN to the order the elements appear in the RFC 2253 table
* <p>
* https://www.ietf.org/rfc/rfc2253.txt
* <p>
* String X.500 AttributeType
* ------------------------------
* CN commonName
* L localityName
* ST stateOrProvinceName
* O organizationName
* OU organizationalUnitName
* C countryName
* STREET streetAddress
* DC domainComponent
* UID userid
*
* @param dn a possibly unordered DN
* @return the ordered dn
*/
public static String reorderDn(String dn) {
RDN[] rdNs = new X500Name(dn).getRDNs();
Arrays.sort(rdNs, new Comparator<RDN>() {
@Override
public int compare(RDN o1, RDN o2) {
AttributeTypeAndValue o1First = o1.getFirst();
AttributeTypeAndValue o2First = o2.getFirst();
ASN1ObjectIdentifier o1Type = o1First.getType();
ASN1ObjectIdentifier o2Type = o2First.getType();
Integer o1Rank = dnOrderMap.get(o1Type);
Integer o2Rank = dnOrderMap.get(o2Type);
if (o1Rank == null) {
if (o2Rank == null) {
int idComparison = o1Type.getId().compareTo(o2Type.getId());
if (idComparison != 0) {
return idComparison;
}
return String.valueOf(o1Type).compareTo(String.valueOf(o2Type));
}
return 1;
} else if (o2Rank == null) {
return -1;
}
return o1Rank - o2Rank;
}
});
return new X500Name(rdNs).toString();
}
示例9
private String getDistributionPointNameString(DistributionPointName distributionPointName, String baseIndent)
throws IOException {
// @formatter:off
/*
* DistributionPointName ::= CHOICE {
* fullname [0] GeneralNames,
* nameRelativeToCRLIssuer [1] RelativeDistinguishedName
* }
*
* RelativeDistinguishedName ::= SET SIZE (1 .. MAX) OF
* AttributeTypeAndValue
*
* AttributeTypeAndValue ::= ASN1Sequence { type AttributeType, value
* AttributeValue }
*/
// @formatter: on
StringBuilder sb = new StringBuilder();
sb.append(baseIndent);
sb.append(res.getString("DistributionPointName"));
sb.append(NEWLINE);
if (distributionPointName.getType() == DistributionPointName.FULL_NAME) {
sb.append(baseIndent);
sb.append(INDENT);
sb.append(res.getString("DistributionPointFullName"));
sb.append(NEWLINE);
GeneralNames generalNames = GeneralNames.getInstance(distributionPointName.getName());
for (GeneralName generalName : generalNames.getNames()) {
sb.append(baseIndent);
sb.append(INDENT);
sb.append(INDENT);
sb.append(GeneralNameUtil.toString(generalName));
sb.append(NEWLINE);
}
} else {
// DistributionPointName.TAG_NAMERELATIVETOCRLISSUER
sb.append(baseIndent);
sb.append(INDENT);
sb.append(res.getString("DistributionPointNameRelativeToCrlIssuer"));
sb.append(NEWLINE);
RDN rdn = RDN.getInstance(distributionPointName.getName());
for (AttributeTypeAndValue attributeTypeAndValue : rdn.getTypesAndValues()) {
ASN1ObjectIdentifier attributeType = attributeTypeAndValue.getType();
ASN1Encodable attributeValue = attributeTypeAndValue.getValue();
String attributeTypeStr = getAttributeTypeString(attributeType);
String attributeValueStr = getAttributeValueString(attributeType, attributeValue);
sb.append(baseIndent);
sb.append(INDENT);
sb.append(INDENT);
sb.append(MessageFormat.format("{0}={1}", attributeTypeStr, attributeValueStr));
sb.append(NEWLINE);
}
}
return sb.toString();
}
示例10
@Test
public void signWithNationalCertificate() throws Exception {
Security.addProvider(new BouncyCastleProvider());
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA", BouncyCastleProvider.PROVIDER_NAME);
keyGen.initialize(1024, new SecureRandom());
Date validityBeginDate = new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000);
long add = (1L * 365L * 24L * 60L * 60L * 1000L); //1 year
Date validityEndDate = new Date(System.currentTimeMillis() + add);
KeyPair keyPair = keyGen.generateKeyPair();
X509Certificate certWithNationalSymbols;
{
//generate certificate with national symbols in DN
X500NameBuilder x500NameBuilder = new X500NameBuilder();
AttributeTypeAndValue attr = new AttributeTypeAndValue(RFC4519Style.cn, commonName);
x500NameBuilder.addRDN(attr);
X500Name dn = x500NameBuilder.build();
X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(
dn, // issuer authority
BigInteger.valueOf(new Random().nextInt()), //serial number of certificate
validityBeginDate, // start of validity
validityEndDate, //end of certificate validity
dn, // subject name of certificate
keyPair.getPublic()); // public key of certificate
// key usage restrictions
builder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.keyCertSign
| KeyUsage.digitalSignature | KeyUsage.keyEncipherment
| KeyUsage.dataEncipherment | KeyUsage.cRLSign));
builder.addExtension(Extension.basicConstraints, false, new BasicConstraints(true));
certWithNationalSymbols = new JcaX509CertificateConverter().getCertificate(builder
.build(new JcaContentSignerBuilder("SHA256withRSA").setProvider(BouncyCastleProvider.PROVIDER_NAME).
build(keyPair.getPrivate())));
}
XadesSigner signer = new XadesBesSigningProfile(new DirectKeyingDataProvider(certWithNationalSymbols, keyPair.getPrivate())).newSigner();
Document doc1 = getTestDocument();
Element elemToSign = doc1.getDocumentElement();
DataObjectDesc obj1 = new DataObjectReference('#' + elemToSign.getAttribute("Id")).withTransform(new EnvelopedSignatureTransform());
SignedDataObjects signDataObject = new SignedDataObjects(obj1);
signer.sign(signDataObject, doc1.getDocumentElement());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
outputDOM(doc1, baos);
String str = new String(baos.toByteArray());
//expected without parsing exception
Document doc = parseDocument(new ByteArrayInputStream(baos.toByteArray()));
}
示例11
private ValidationIssue checkSubjectAttributeNotMultiValued(ASN1ObjectIdentifier type,
X500Name subject, X500Name requestedSubject) throws BadCertTemplateException {
ValidationIssue issue = createSubjectIssue(type);
// control
RdnControl rdnControl = subjectControl.getControl(type);
int minOccurs = (rdnControl == null) ? 0 : rdnControl.getMinOccurs();
int maxOccurs = (rdnControl == null) ? 0 : rdnControl.getMaxOccurs();
RDN[] rdns = subject.getRDNs(type);
int rdnsSize = (rdns == null) ? 0 : rdns.length;
if (rdnsSize < minOccurs || rdnsSize > maxOccurs) {
issue.setFailureMessage("number of RDNs '" + rdnsSize
+ "' is not within [" + minOccurs + ", " + maxOccurs + "]");
return issue;
}
List<String> requestedCoreAtvTextValues = new LinkedList<>();
RDN[] requestedRdns = requestedSubject.getRDNs(type);
if (rdnControl == null || rdnControl.isValueOverridable()) {
if (requestedRdns != null && requestedRdns.length > 0) {
for (RDN requestedRdn : requestedRdns) {
String textValue = getRdnTextValueOfRequest(requestedRdn);
requestedCoreAtvTextValues.add(textValue);
}
} else if (rdnControl != null && rdnControl.getValue() != null) {
requestedCoreAtvTextValues.add(rdnControl.getValue());
}
} else {
// rdnControl.getValue() could not be non-null here.
requestedCoreAtvTextValues.add(rdnControl.getValue());
}
if (rdnsSize == 0) {
// check optional attribute but is present in requestedSubject
if (maxOccurs > 0 && !requestedCoreAtvTextValues.isEmpty()) {
issue.setFailureMessage("is absent but expected present");
}
return issue;
}
StringBuilder failureMsg = new StringBuilder();
// check the encoding
StringType stringType = null;
if (rdnControl != null) {
stringType = rdnControl.getStringType();
}
if (stringType == null) {
stringType = StringType.utf8String;
}
for (int i = 0; i < rdns.length; i++) {
RDN rdn = rdns[i];
AttributeTypeAndValue[] atvs = rdn.getTypesAndValues();
if (atvs.length > 1) {
failureMsg.append("size of RDN[" + i + "] is '" + atvs.length + "' but expected '1'");
failureMsg.append("; ");
continue;
}
String atvTextValue = getAtvValueString("RDN[" + i + "]", atvs[0], stringType, failureMsg);
if (atvTextValue == null) {
continue;
}
checkAttributeTypeAndValue("RDN[" + i + "]", type, atvTextValue, rdnControl,
requestedCoreAtvTextValues, i, failureMsg);
}
int len = failureMsg.length();
if (len > 2) {
failureMsg.delete(len - 2, len);
issue.setFailureMessage(failureMsg.toString());
}
return issue;
}
示例12
private ValidationIssue checkSubjectAttributeMultiValued(ASN1ObjectIdentifier type,
X500Name subject, X500Name requestedSubject) throws BadCertTemplateException {
ValidationIssue issue = createSubjectIssue(type);
RDN[] rdns = subject.getRDNs(type);
int rdnsSize = (rdns == null) ? 0 : rdns.length;
RDN[] requestedRdns = requestedSubject.getRDNs(type);
if (rdnsSize != 1) {
if (rdnsSize == 0) {
// check optional attribute but is present in requestedSubject
if (requestedRdns != null && requestedRdns.length > 0) {
issue.setFailureMessage("is absent but expected present");
}
} else {
issue.setFailureMessage("number of RDNs '" + rdnsSize + "' is not 1");
}
return issue;
}
// control
final RdnControl rdnControl = subjectControl.getControl(type);
// check the encoding
StringType stringType = null;
if (rdnControl != null) {
stringType = rdnControl.getStringType();
}
List<String> requestedCoreAtvTextValues = new LinkedList<>();
if (requestedRdns != null) {
for (RDN requestedRdn : requestedRdns) {
String textValue = getRdnTextValueOfRequest(requestedRdn);
requestedCoreAtvTextValues.add(textValue);
}
}
if (rdns == null) { // return always false, only to make the null checker happy
return issue;
}
StringBuilder failureMsg = new StringBuilder();
AttributeTypeAndValue[] li = rdns[0].getTypesAndValues();
List<AttributeTypeAndValue> atvs = new LinkedList<>();
for (AttributeTypeAndValue m : li) {
if (type.equals(m.getType())) {
atvs.add(m);
}
}
final int atvsSize = atvs.size();
int minOccurs = (rdnControl == null) ? 0 : rdnControl.getMinOccurs();
int maxOccurs = (rdnControl == null) ? 0 : rdnControl.getMaxOccurs();
if (atvsSize < minOccurs || atvsSize > maxOccurs) {
issue.setFailureMessage("number of AttributeTypeAndValuess '" + atvsSize
+ "' is not within [" + minOccurs + ", " + maxOccurs + "]");
return issue;
}
for (int i = 0; i < atvsSize; i++) {
AttributeTypeAndValue atv = atvs.get(i);
String atvTextValue = getAtvValueString("AttributeTypeAndValue[" + i + "]", atv,
stringType, failureMsg);
if (atvTextValue == null) {
continue;
}
checkAttributeTypeAndValue("AttributeTypeAndValue[" + i + "]", type, atvTextValue,
rdnControl, requestedCoreAtvTextValues, i, failureMsg);
}
int len = failureMsg.length();
if (len > 2) {
failureMsg.delete(len - 2, len);
issue.setFailureMessage(failureMsg.toString());
}
return issue;
}
示例13
private static String getAtvValueString(String name, AttributeTypeAndValue atv,
StringType stringType, StringBuilder failureMsg) {
ASN1ObjectIdentifier type = atv.getType();
ASN1Encodable atvValue = atv.getValue();
if (ObjectIdentifiers.DN.dateOfBirth.equals(type)) {
if (!(atvValue instanceof ASN1GeneralizedTime)) {
failureMsg.append(name).append(" is not of type GeneralizedTime; ");
return null;
}
return ((ASN1GeneralizedTime) atvValue).getTimeString();
} else if (ObjectIdentifiers.DN.postalAddress.equals(type)) {
if (!(atvValue instanceof ASN1Sequence)) {
failureMsg.append(name).append(" is not of type Sequence; ");
return null;
}
ASN1Sequence seq = (ASN1Sequence) atvValue;
final int n = seq.size();
StringBuilder sb = new StringBuilder();
boolean validEncoding = true;
for (int i = 0; i < n; i++) {
ASN1Encodable obj = seq.getObjectAt(i);
if (!matchStringType(obj, stringType)) {
failureMsg.append(name).append(".[").append(i).append("] is not of type ")
.append(stringType.name()).append("; ");
validEncoding = false;
break;
}
String textValue = X509Util.rdnValueToString(obj);
sb.append("[").append(i).append("]=").append(textValue).append(",");
}
if (!validEncoding) {
return null;
}
return sb.toString();
} else {
if (!matchStringType(atvValue, stringType)) {
failureMsg.append(name).append(" is not of type " + stringType.name()).append("; ");
return null;
}
return X509Util.rdnValueToString(atvValue);
}
}