use of org.bouncycastle.asn1.ASN1OctetString in project keystore-explorer by kaikramer.
the class X509Ext method getAdmissionStringValue.
private String getAdmissionStringValue(byte[] octets) throws IOException {
// @formatter:off
/*
AdmissionSyntax ::= SEQUENCE
{
admissionAuthority GeneralName OPTIONAL,
contentsOfAdmissions SEQUENCE OF Admissions
}
Admissions ::= SEQUENCE
{
admissionAuthority [0] EXPLICIT GeneralName OPTIONAL
namingAuthority [1] EXPLICIT NamingAuthority OPTIONAL
professionInfos SEQUENCE OF ProfessionInfo
}
NamingAuthority ::= SEQUENCE
{
namingAuthorityId OBJECT IDENTIFIER OPTIONAL,
namingAuthorityUrl IA5String OPTIONAL,
namingAuthorityText DirectoryString(SIZE(1..128)) OPTIONAL
}
ProfessionInfo ::= SEQUENCE
{
namingAuthority [0] EXPLICIT NamingAuthority OPTIONAL,
professionItems SEQUENCE OF DirectoryString (SIZE(1..128)),
professionOIDs SEQUENCE OF OBJECT IDENTIFIER OPTIONAL,
registrationNumber PrintableString(SIZE(1..128)) OPTIONAL,
addProfessionInfo OCTET STRING OPTIONAL
}
*/
// @formatter:on
StringBuilder sb = new StringBuilder();
int indentLevel = 1;
AdmissionSyntax admissionSyntax = AdmissionSyntax.getInstance(ASN1Sequence.getInstance(octets));
GeneralName admissionAuthority = admissionSyntax.getAdmissionAuthority();
if (admissionAuthority != null) {
sb.append(MessageFormat.format(res.getString("Admission.AdmissionAuthority"), GeneralNameUtil.toString(admissionAuthority)));
sb.append(NEWLINE);
}
Admissions[] admissions = admissionSyntax.getContentsOfAdmissions();
int admissionNr = 0;
for (Admissions admission : admissions) {
sb.append(MessageFormat.format(res.getString("Admission.Admission"), ++admissionNr));
sb.append(NEWLINE);
admissionAuthority = admission.getAdmissionAuthority();
NamingAuthority namingAuthority = admission.getNamingAuthority();
ProfessionInfo[] professionInfos = admission.getProfessionInfos();
if (admissionAuthority != null) {
sb.append(INDENT.toString(indentLevel));
sb.append(MessageFormat.format(res.getString("Admission.AdmissionAuthority"), GeneralNameUtil.toString(admissionAuthority)));
sb.append(NEWLINE);
}
if (namingAuthority != null) {
sb.append(getNamingAuthorityStringValue(namingAuthority, indentLevel));
}
for (ProfessionInfo professionInfo : professionInfos) {
namingAuthority = professionInfo.getNamingAuthority();
ASN1ObjectIdentifier[] professionOIDs = professionInfo.getProfessionOIDs();
String registrationNumber = professionInfo.getRegistrationNumber();
ASN1OctetString addProfessionInfo = professionInfo.getAddProfessionInfo();
sb.append(INDENT.toString(indentLevel));
sb.append(res.getString("Admission.ProfessionInfo"));
sb.append(NEWLINE);
indentLevel++;
if (namingAuthority != null) {
sb.append(getNamingAuthorityStringValue(namingAuthority, indentLevel));
}
DirectoryString[] professionItems = professionInfo.getProfessionItems();
for (DirectoryString professionItem : professionItems) {
sb.append(INDENT.toString(indentLevel));
sb.append(MessageFormat.format(res.getString("Admission.ProfessionItem"), professionItem.toString()));
sb.append(NEWLINE);
}
if (professionOIDs != null) {
for (ASN1ObjectIdentifier professionOID : professionOIDs) {
sb.append(INDENT.toString(indentLevel));
sb.append(MessageFormat.format(res.getString("Admission.ProfessionOID"), professionOID.getId()));
sb.append(NEWLINE);
}
}
if (registrationNumber != null) {
sb.append(INDENT.toString(indentLevel));
sb.append(MessageFormat.format(res.getString("Admission.RegistrationNumber"), registrationNumber));
sb.append(NEWLINE);
}
if (addProfessionInfo != null) {
sb.append(INDENT.toString(indentLevel));
sb.append(MessageFormat.format(res.getString("Admission.AddProfessionInfo"), HexUtil.getHexString(addProfessionInfo.getOctets())));
sb.append(NEWLINE);
}
indentLevel--;
}
}
return sb.toString();
}
use of org.bouncycastle.asn1.ASN1OctetString in project keystore-explorer by kaikramer.
the class GeneralNameUtil method safeToString.
// @formatter:off
/*
* GeneralName ::= CHOICE
* {
* otherName [0] AnotherName,
* rfc822Name [1] DERIA5String,
* dNSName [2] DERIA5String,
* x400Address [3] ORAddress,
* directoryName [4] Name,
* ediPartyName [5] EDIPartyName,
* uniformResourceIdentifier [6] DERIA5String,
* iPAddress [7] OCTET STRING,
* registeredID [8] OBJECT IDENTIFIER
* }
*
* AnotherName ::= ASN1Sequence
* {
* type-id OBJECT IDENTIFIER,
* value [0] EXPLICIT ANY DEFINED BY type-id
* }
*
* EDIPartyName ::= ASN1Sequence
* {
* nameAssigner [0] DirectoryString OPTIONAL,
* partyName [1] DirectoryString
* }
*
* DirectoryString ::= CHOICE
* {
* teletexString TeletexString (SIZE (1..MAX),
* printableString PrintableString (SIZE (1..MAX)),
* universalString UniversalString (SIZE (1..MAX)),
* utf8String UTF8String (SIZE (1.. MAX)),
* bmpString BMPString (SIZE(1..MAX))
* }
*/
// @formatter:on
/**
* Get string representation for General names that cannot cause a
* IOException to be thrown. Unsupported are ediPartyName, otherName and
* x400Address. Returns a blank string for these.
*
* @param generalName
* General name
* @param addLinkForURI
* If true, convert URI to a clickable link
* @return String representation of general name
*/
public static String safeToString(GeneralName generalName, boolean addLinkForURI) {
if (generalName == null) {
return "";
}
switch(generalName.getTagNo()) {
case GeneralName.directoryName:
X500Name directoryName = (X500Name) generalName.getName();
return MessageFormat.format(res.getString("GeneralNameUtil.DirectoryGeneralName"), directoryName.toString());
case GeneralName.dNSName:
DERIA5String dnsName = (DERIA5String) generalName.getName();
return MessageFormat.format(res.getString("GeneralNameUtil.DnsGeneralName"), dnsName.getString());
case GeneralName.iPAddress:
byte[] ipAddressBytes = ((ASN1OctetString) generalName.getName()).getOctets();
String ipAddressString = "";
try {
ipAddressString = InetAddress.getByAddress(ipAddressBytes).getHostAddress();
} catch (UnknownHostException e) {
// ignore -> results in empty IP address string
}
return MessageFormat.format(res.getString("GeneralNameUtil.IpAddressGeneralName"), ipAddressString);
case GeneralName.registeredID:
ASN1ObjectIdentifier registeredId = (ASN1ObjectIdentifier) generalName.getName();
return MessageFormat.format(res.getString("GeneralNameUtil.RegisteredIdGeneralName"), ObjectIdUtil.toString(registeredId));
case GeneralName.rfc822Name:
DERIA5String rfc822Name = (DERIA5String) generalName.getName();
return MessageFormat.format(res.getString("GeneralNameUtil.Rfc822GeneralName"), rfc822Name.getString());
case GeneralName.uniformResourceIdentifier:
DERIA5String uri = (DERIA5String) generalName.getName();
String link = addLinkForURI ? "<a href=\"" + uri.getString() + "\">" + uri.getString() + "</a>" : uri.getString();
return MessageFormat.format(res.getString("GeneralNameUtil.UriGeneralName"), link);
case GeneralName.otherName:
// we currently only support UPN in otherName
String upn = parseUPN(generalName);
return MessageFormat.format(res.getString("GeneralNameUtil.OtherGeneralName"), "UPN", upn);
default:
return "";
}
}
use of org.bouncycastle.asn1.ASN1OctetString in project ddf by codice.
the class SamlAssertionValidatorImpl method validateHolderOfKeyConfirmation.
private void validateHolderOfKeyConfirmation(SamlAssertionWrapper assertion, X509Certificate[] x509Certs) throws SecurityServiceException {
List<String> confirmationMethods = assertion.getConfirmationMethods();
boolean hasHokMethod = false;
for (String method : confirmationMethods) {
if (OpenSAMLUtil.isMethodHolderOfKey(method)) {
hasHokMethod = true;
}
}
if (hasHokMethod) {
if (x509Certs != null && x509Certs.length > 0) {
List<SubjectConfirmation> subjectConfirmations = assertion.getSaml2().getSubject().getSubjectConfirmations();
for (SubjectConfirmation subjectConfirmation : subjectConfirmations) {
if (OpenSAMLUtil.isMethodHolderOfKey(subjectConfirmation.getMethod())) {
Element dom = subjectConfirmation.getSubjectConfirmationData().getDOM();
Node keyInfo = dom.getFirstChild();
Node x509Data = keyInfo.getFirstChild();
Node dataNode = x509Data.getFirstChild();
Node dataText = dataNode.getFirstChild();
X509Certificate tlsCertificate = x509Certs[0];
if (dataNode.getLocalName().equals("X509Certificate")) {
String textContent = dataText.getTextContent();
byte[] byteValue = Base64.getMimeDecoder().decode(textContent);
try {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(byteValue));
// check that the certificate is still valid
cert.checkValidity();
// if the certs aren't the same, verify
if (!tlsCertificate.equals(cert)) {
// verify that the cert was signed by the same private key as the TLS cert
cert.verify(tlsCertificate.getPublicKey());
}
} catch (CertificateException | NoSuchAlgorithmException | InvalidKeyException | SignatureException | NoSuchProviderException e) {
throw new SecurityServiceException("Unable to validate Holder of Key assertion with certificate.");
}
} else if (dataNode.getLocalName().equals("X509SubjectName")) {
String textContent = dataText.getTextContent();
// the assertion.
if (!tlsCertificate.getSubjectDN().getName().equals(textContent)) {
throw new SecurityServiceException("Unable to validate Holder of Key assertion with subject DN.");
}
} else if (dataNode.getLocalName().equals("X509IssuerSerial")) {
// we have no way to support this confirmation type so we have to throw an error
throw new SecurityServiceException("Unable to validate Holder of Key assertion with issuer serial. NOT SUPPORTED");
} else if (dataNode.getLocalName().equals("X509SKI")) {
String textContent = dataText.getTextContent();
byte[] tlsSKI = tlsCertificate.getExtensionValue("2.5.29.14");
byte[] assertionSKI = Base64.getMimeDecoder().decode(textContent);
if (tlsSKI != null && tlsSKI.length > 0) {
ASN1OctetString tlsOs = ASN1OctetString.getInstance(tlsSKI);
ASN1OctetString assertionOs = ASN1OctetString.getInstance(assertionSKI);
SubjectKeyIdentifier tlsSubjectKeyIdentifier = SubjectKeyIdentifier.getInstance(tlsOs.getOctets());
SubjectKeyIdentifier assertSubjectKeyIdentifier = SubjectKeyIdentifier.getInstance(assertionOs.getOctets());
// assertion.
if (!Arrays.equals(tlsSubjectKeyIdentifier.getKeyIdentifier(), assertSubjectKeyIdentifier.getKeyIdentifier())) {
throw new SecurityServiceException("Unable to validate Holder of Key assertion with subject key identifier.");
}
} else {
throw new SecurityServiceException("Unable to validate Holder of Key assertion with subject key identifier.");
}
}
}
}
} else {
throw new SecurityServiceException("Holder of Key assertion, must be used with 2-way TLS.");
}
}
}
use of org.bouncycastle.asn1.ASN1OctetString in project zm-mailbox by Zimbra.
the class UBIDLdapContext method searchPaged.
@Override
public void searchPaged(SearchLdapOptions searchOptions) throws ServiceException {
int maxResults = searchOptions.getMaxResults();
String base = searchOptions.getSearchBase();
ZLdapFilter filter = searchOptions.getFilter();
Set<String> binaryAttrs = searchOptions.getBinaryAttrs();
SearchScope searchScope = ((UBIDSearchScope) searchOptions.getSearchScope()).getNative();
SearchLdapOptions.SearchLdapVisitor visitor = searchOptions.getVisitor();
SearchGalResult searchGalResult = searchOptions.getSearchGalResult();
int pageSize = searchOptions.getResultPageSize();
int offset = 0;
boolean pagination = false;
int limit = 0;
String prevLastReturnedItemCreateDate = null;
if (searchGalResult != null) {
offset = searchGalResult.getLdapMatchCount();
prevLastReturnedItemCreateDate = searchGalResult.getLdapTimeStamp();
pagination = searchGalResult.getHadMore();
limit = searchGalResult.getLimit();
}
if (GalOp.sync == searchOptions.getGalOp() && !pagination) {
limit = 0;
}
if (limit == 0) {
limit = Integer.MAX_VALUE;
}
int pageCount = 0;
int pageOffset = 0;
int currentPage = 0;
int index = 0;
if (offset > 0) {
pageCount = offset / pageSize;
pageOffset = offset % pageSize;
}
String newToken = "";
// TODO: this is the legacy behavior, we can make it a param
boolean wantPartialResult = true;
try {
SearchRequest searchRequest = new SearchRequest(base, searchScope, derefAliasPolicy, maxResults, 0, false, ((UBIDLdapFilter) filter).getNative());
searchRequest.setAttributes(searchOptions.getReturnAttrs());
// Set the page size and initialize the cookie that we pass back in subsequent pages
ASN1OctetString cookie = null;
int count = offset;
do {
List<Control> controls = Lists.newArrayListWithCapacity(2);
if (searchOptions.isUseControl()) {
controls.add(new SimplePagedResultsControl(pageSize, cookie));
}
if (searchOptions.isManageDSAit()) {
controls.add(new ManageDsaITRequestControl(false));
}
searchRequest.setControls(controls.toArray(new Control[0]));
SearchResult result = null;
try {
result = UBIDLdapOperation.SEARCH.execute(this, searchRequest, filter);
} catch (LDAPException e) {
if (ResultCode.SIZE_LIMIT_EXCEEDED == e.getResultCode() && wantPartialResult) {
// if callsite wants partial result, return them
LDAPResult ldapResult = e.toLDAPResult();
if (ldapResult instanceof SearchResult) {
SearchResult searchResult = (SearchResult) ldapResult;
for (SearchResultEntry entry : searchResult.getSearchEntries()) {
String dn = entry.getDN();
UBIDAttributes ubidAttrs = new UBIDAttributes(entry);
if (visitor.wantAttrMapOnVisit()) {
visitor.visit(dn, ubidAttrs.getAttrs(binaryAttrs), ubidAttrs);
} else {
visitor.visit(dn, ubidAttrs);
}
newToken = ubidAttrs.getAttrString("whenCreated") != null ? ubidAttrs.getAttrString("whenCreated") : ubidAttrs.getAttrString("createTimeStamp");
}
if (searchGalResult != null) {
searchGalResult.setLdapTimeStamp(newToken);
searchGalResult.setLdapMatchCount(1);
searchGalResult.setHadMore(true);
}
}
}
// always re-throw
throw e;
}
List<SearchResultEntry> entries = result.getSearchEntries();
boolean hasMore = false;
int resultSize = entries.size();
if (resultSize > (limit + pageOffset)) {
hasMore = true;
}
String leCreateDate = null;
if (currentPage >= pageCount) {
leCreateDate = getLastEntryCreationDate(limit + pageOffset, entries);
if (prevLastReturnedItemCreateDate != null && !prevLastReturnedItemCreateDate.equals(leCreateDate)) {
count = 0;
}
for (index = pageOffset; index < entries.size() && limit > 0; index++) {
SearchResultEntry entry = entries.get(index);
String dn = entry.getDN();
UBIDAttributes ubidAttrs = new UBIDAttributes(entry);
if (visitor.wantAttrMapOnVisit()) {
visitor.visit(dn, ubidAttrs.getAttrs(binaryAttrs), ubidAttrs);
} else {
visitor.visit(dn, ubidAttrs);
}
limit--;
newToken = ubidAttrs.getAttrString("whenCreated") != null ? ubidAttrs.getAttrString("whenCreated") : ubidAttrs.getAttrString("createTimeStamp");
if (newToken != null && newToken.equals(leCreateDate)) {
count++;
}
}
prevLastReturnedItemCreateDate = leCreateDate;
pageOffset = 0;
}
cookie = null;
for (Control c : result.getResponseControls()) {
if (c instanceof SimplePagedResultsControl) {
cookie = ((SimplePagedResultsControl) c).getCookie();
}
}
if (searchGalResult != null && (GalOp.sync == searchOptions.getGalOp())) {
if (limit == 0 && (((cookie != null) && (cookie.getValueLength() > 0)) || hasMore)) {
searchGalResult.setHadMore(true);
searchGalResult.setLdapTimeStamp(newToken);
searchGalResult.setLdapMatchCount(count);
} else if (((cookie != null) && (cookie.getValueLength() == 0))) {
searchGalResult.setHadMore(false);
searchGalResult.setLdapMatchCount(0);
}
}
currentPage++;
} while ((cookie != null) && (cookie.getValueLength() > 0) && limit > 0);
} catch (SearchLdapOptions.StopIteratingException e) {
// break out of the loop and close the ne
} catch (LDAPException e) {
throw mapToLdapException("unable to search ldap", e);
}
}
use of org.bouncycastle.asn1.ASN1OctetString in project zm-mailbox by Zimbra.
the class UBIDMutableEntry method mapToAttrs.
// ZMutableEntry
@Override
public void mapToAttrs(Map<String, Object> mapAttrs) {
AttributeManager attrMgr = AttributeManager.getInst();
for (Map.Entry<String, Object> me : mapAttrs.entrySet()) {
String attrName = me.getKey();
Object v = me.getValue();
boolean containsBinaryData = attrMgr == null ? false : attrMgr.containsBinaryData(attrName);
boolean isBinaryTransfer = attrMgr == null ? false : attrMgr.isBinaryTransfer(attrName);
if (v instanceof String) {
ASN1OctetString value = UBIDUtil.newASN1OctetString(containsBinaryData, (String) v);
Attribute a = UBIDUtil.newAttribute(isBinaryTransfer, attrName, value);
entry.addAttribute(a);
} else if (v instanceof String[]) {
String[] sa = (String[]) v;
ASN1OctetString[] values = new ASN1OctetString[sa.length];
for (int i = 0; i < sa.length; i++) {
values[i] = UBIDUtil.newASN1OctetString(containsBinaryData, sa[i]);
}
Attribute a = UBIDUtil.newAttribute(isBinaryTransfer, attrName, values);
entry.addAttribute(a);
} else if (v instanceof Collection) {
Collection c = (Collection) v;
ASN1OctetString[] values = new ASN1OctetString[c.size()];
int i = 0;
for (Object o : c) {
values[i] = UBIDUtil.newASN1OctetString(containsBinaryData, o.toString());
i++;
}
Attribute a = UBIDUtil.newAttribute(isBinaryTransfer, attrName, values);
entry.addAttribute(a);
}
}
}
Aggregations