use of com.mindbright.security.x509.Attribute in project vos by opencadc.
the class TransferReader method parseTransfer.
private Transfer parseTransfer(Document document, String targetScheme) throws URISyntaxException {
Element root = document.getRootElement();
Namespace vosNS = root.getNamespace();
Attribute versionAttr = root.getAttribute("version");
int version;
if (VOSPACE_NS_20.equals(vosNS.getURI())) {
version = VOS.VOSPACE_20;
// Check the minor version attribute
if (versionAttr != null && VOSPACE_MINOR_VERSION_21.equals(versionAttr.getValue())) {
version = VOS.VOSPACE_21;
}
} else {
throw new IllegalArgumentException("unexpected VOSpace namespace: " + vosNS.getURI());
}
Direction direction = parseDirection(root, vosNS);
// String serviceUrl; // not in XML yet
List<URI> targets = parseTargets(root, vosNS, targetScheme);
View view = null;
Parameter param = null;
List views = root.getChildren("view", vosNS);
if (views != null && views.size() > 0) {
Element v = (Element) views.get(0);
view = new View(new URI(v.getAttributeValue("uri")));
List params = v.getChildren("param", vosNS);
if (params != null) {
for (Object o : params) {
Element p = (Element) o;
param = new Parameter(new URI(p.getAttributeValue("uri")), p.getText());
view.getParameters().add(param);
}
}
}
List<Protocol> protocols = parseProtocols(root, vosNS, version);
String keepBytesStr = root.getChildText("keepBytes", vosNS);
boolean keepBytes = true;
if (keepBytesStr != null)
keepBytes = keepBytesStr.equalsIgnoreCase("true");
Transfer ret = new Transfer(direction);
ret.getTargets().addAll(targets);
ret.setView(view);
if (protocols != null) {
// parseProtocols() above can potentially return null
ret.getProtocols().addAll(protocols);
}
ret.setKeepBytes(keepBytes);
ret.version = version;
// optional param(s) added in VOSpace-2.1
if (version >= VOS.VOSPACE_21) {
List<Element> params = root.getChildren("param", vosNS);
for (Element pe : params) {
String uri = pe.getAttributeValue("uri");
if (VOS.PROPERTY_URI_CONTENTLENGTH.equals(uri)) {
try {
ret.setContentLength(new Long(pe.getText()));
} catch (NumberFormatException ex) {
throw new IllegalArgumentException("invalid " + VOS.PROPERTY_URI_CONTENTLENGTH + ": " + pe.getText());
}
} else {
log.debug("skip unknown param: " + uri);
}
}
}
return ret;
}
use of com.mindbright.security.x509.Attribute in project OpenAttestation by OpenAttestation.
the class X509AttributeCertificate method valueOf.
/**
*
* @param encodedCertificate
* @return
*/
@JsonCreator
public static X509AttributeCertificate valueOf(@JsonProperty("encoded") byte[] encodedCertificate) {
X509AttributeCertificate result = new X509AttributeCertificate(encodedCertificate);
X509AttributeCertificateHolder cert;
try {
cert = new X509AttributeCertificateHolder(encodedCertificate);
} catch (IOException e) {
throw new IllegalArgumentException(e);
}
// calls toString() on each X500Name so we get the default representation; we can do it ourselves for custom display; output example: CN=Attr CA,OU=CPG,OU=DCSG,O=Intel,ST=CA,C=US
log.debug("issuer: {}", StringUtils.join(cert.getIssuer().getNames(), "; "));
// but expected to be only one
result.issuer = StringUtils.join(cert.getIssuer().getNames(), "; ");
// output example: 1
log.debug("serial number: {}", cert.getSerialNumber().toString());
result.serialNumber = cert.getSerialNumber();
// output example: 2.25=#041092a71a228c174522a18bfd3ed3d00b39
log.debug("holder: {}", StringUtils.join(cert.getHolder().getEntityNames(), ", "));
// now let's get the UUID specifically out of this
log.debug("holder has {} entity names", cert.getHolder().getEntityNames().length);
for (X500Name entityName : cert.getHolder().getEntityNames()) {
log.debug("holder entity name has {} rdns", entityName.getRDNs().length);
for (RDN rdn : entityName.getRDNs()) {
log.debug("entity rdn is multivalued? {}", rdn.isMultiValued());
AttributeTypeAndValue attr = rdn.getFirst();
if (attr.getType().toString().equals(OID.HOST_UUID)) {
UUID uuid = UUID.valueOf(DEROctetString.getInstance(attr.getValue()).getOctets());
log.debug("holder uuid: {}", uuid);
// example: 33766a63-5c55-4461-8a84-5936577df450
result.subject = uuid.toString();
}
}
}
// if we ddin't identify the UUID, just display the subject same way we did the issuer... concat all the entity names. example: 2.25=#041033766a635c5544618a845936577df450 (notice that in the value, there's a #0410 prepended to the uuid 33766a635c5544618a845936577df450)
if (result.subject == null) {
result.subject = StringUtils.join(cert.getHolder().getEntityNames(), "; ");
}
// output example: Thu Aug 08 15:21:13 PDT 2013
log.debug("not before: {}", cert.getNotBefore());
// output example: Sun Sep 08 15:21:13 PDT 2013
log.debug("not after: {}", cert.getNotAfter());
result.notBefore = cert.getNotBefore();
result.notAfter = cert.getNotAfter();
Attribute[] attributes = cert.getAttributes();
result.tags1 = new ArrayList<UTF8NameValueMicroformat>();
result.tags2 = new ArrayList<UTF8NameValueSequence>();
result.tagsOther = new ArrayList<ASN1Encodable>();
for (Attribute attr : attributes) {
log.debug("attr {} is {}", attr.hashCode(), attr.toString());
result.attributes.add(attr);
for (ASN1Encodable value : attr.getAttributeValues()) {
// result.tags.add(new AttributeOidAndValue(attr.getAttrType().toString(), DERUTF8String.getInstance(value).getString()));
if (attr.getAttrType().toString().equals(UTF8NameValueMicroformat.OID)) {
// our values are just UTF-8 strings but if you use new String(value.getEncoded()) you will get two extra spaces at the beginning of the string
log.debug("name-value microformat attribute: {}", DERUTF8String.getInstance(value).getString());
UTF8NameValueMicroformat microformat = new UTF8NameValueMicroformat(DERUTF8String.getInstance(value));
log.debug("name-value microformat attribute (2) name {} value {}", microformat.getName(), microformat.getValue());
result.tags1.add(microformat);
} else if (attr.getAttrType().toString().equals(UTF8NameValueSequence.OID)) {
UTF8NameValueSequence sequence = new UTF8NameValueSequence(ASN1Sequence.getInstance(value));
String name = sequence.getName();
List<String> values = sequence.getValues();
log.debug("name-values asn.1 attribute {} values {}", name, values);
result.tags2.add(sequence);
} else {
log.debug("unrecognzied attribute type {}", attr.getAttrType().toString());
result.tagsOther.add(value);
}
/*
* output examples:
* attribute: 1.3.6.1.4.1.99999.1.1.1.1 is US
* attribute: 1.3.6.1.4.1.99999.2.2.2.2 is CA
* attribute: 1.3.6.1.4.1.99999.3.3.3.3 is Folsom
*/
}
}
log.debug("valueOf ok");
return result;
}
use of com.mindbright.security.x509.Attribute in project OpenAttestation by OpenAttestation.
the class CertificateRepository method create.
@Override
public // @RequiresPermissions("tag_certificates:create")
void create(Certificate item) {
log.debug("Certificate:Create - Got request to create a new Certificate {}.", item.getId().toString());
CertificateLocator locator = new CertificateLocator();
locator.id = item.getId();
try (CertificateDAO dao = TagJdbi.certificateDao()) {
Certificate newCert = dao.findById(item.getId());
if (newCert == null) {
newCert = Certificate.valueOf(item.getCertificate());
dao.insert(item.getId(), newCert.getCertificate(), newCert.getSha1().toHexString(), newCert.getSha256().toHexString(), newCert.getSubject(), newCert.getIssuer(), newCert.getNotBefore(), newCert.getNotAfter());
log.debug("Certificate:Create - Created the Certificate {} successfully.", item.getId().toString());
} else {
log.error("Certificate:Create - Certificate {} will not be created since a duplicate Certificate already exists.", item.getId().toString());
throw new RepositoryCreateConflictException(locator);
}
} catch (RepositoryException re) {
throw re;
} catch (Exception ex) {
log.error("Certificate:Create - Error during certificate creation.", ex);
throw new RepositoryCreateException(ex, locator);
}
//Store tag values from Certificate
try {
log.info("Tags from certificate will now be stored");
KvAttributeRepository repository = new KvAttributeRepository();
KvAttribute kvAttrib = new KvAttribute();
if (kvAttrib == null || repository == null)
log.debug("kvAttrib or repository Obj is null, unable to store certificate tags");
else {
List<Attribute> certAttributes = X509AttributeCertificate.valueOf(item.getCertificate()).getAttribute();
for (Attribute attr : certAttributes) {
for (ASN1Encodable value : attr.getAttributeValues()) {
if (attr.getAttrType().toString().equals(UTF8NameValueMicroformat.OID)) {
UTF8NameValueMicroformat microformat = new UTF8NameValueMicroformat(DERUTF8String.getInstance(value));
// Check if that tag with same value already exists
KvAttributeFilterCriteria criteria = new KvAttributeFilterCriteria();
criteria.nameEqualTo = microformat.getName();
criteria.valueEqualTo = microformat.getValue();
KvAttributeCollection results = repository.search(criteria);
if (results.getDocuments().isEmpty()) {
kvAttrib.setId(new UUID());
kvAttrib.setName(microformat.getName());
kvAttrib.setValue(microformat.getValue());
repository.create(kvAttrib);
} else
log.debug("Tag with Name:{} & Value:{} is already stored.", microformat.getName(), microformat.getValue());
}
}
}
}
} catch (Exception e) {
log.error("Certificate:Create - Error during attribute scan", e);
}
}
use of com.mindbright.security.x509.Attribute in project OpenAttestation by OpenAttestation.
the class ProvisionTagCertificate method certificateAttributesEqual.
//
// /**
// * Check that the attributes in the certificate are the same as the attributes in the given selection.
// * The order is not considered so they do not have to be in the same order.
// *
// * The given selection must have inline attributes (not requiring any lookup by id or name).
// *
// * @return true if the attribute certificate has exactly the same attributes as in the given selection
// */
protected boolean certificateAttributesEqual(X509AttributeCertificate certificate, SelectionType selection) throws IOException {
List<Attribute> certAttributes = certificate.getAttribute();
// initialized with all false, later we mark individual elements true if they are found within the given selection, so that if any are left false at the end we know that there are attributes in the cert that were not in the selection
boolean[] certAttrMatch = new boolean[certAttributes.size()];
// for every attribute in the selection, check if it's present in the certificate
for (AttributeType xmlAttribute : selection.getAttribute()) {
X509AttrBuilder.Attribute oidAndValue = Util.toAttributeOidValue(xmlAttribute);
// look through the certificate for same oid and value
boolean found = false;
for (int i = 0; i < certAttrMatch.length; i++) {
if (Arrays.equals(certAttributes.get(i).getAttrType().getDEREncoded(), oidAndValue.oid.getDEREncoded())) {
if (Arrays.equals(certAttributes.get(i).getAttributeValues()[0].getDEREncoded(), oidAndValue.value.getDEREncoded())) {
certAttrMatch[i] = true;
found = true;
}
}
}
if (!found) {
log.debug("Certificate does not have attribute oid {} and value {}", Hex.encodeHexString(oidAndValue.oid.getDEREncoded()), Hex.encodeHexString(oidAndValue.value.getDEREncoded()));
return false;
}
}
// check if the certificate has any attributes that are not in the selection
for (int i = 0; i < certAttrMatch.length; i++) {
if (!certAttrMatch[i]) {
log.debug("Selection does not have attribute oid {} and value {}", Hex.encodeHexString(certAttributes.get(i).getAttrType().getDEREncoded()), Hex.encodeHexString(certAttributes.get(i).getAttributeValues()[0].getDEREncoded()));
return false;
}
}
// certificate and selection have same set of attribute (oid,value) pairs
return true;
}
use of com.mindbright.security.x509.Attribute in project android_frameworks_base by ResurrectionRemix.
the class ESTHandler method buildCSR.
private byte[] buildCSR(ByteBuffer octetBuffer, OMADMAdapter omadmAdapter, HTTPHandler httpHandler) throws IOException, GeneralSecurityException {
//Security.addProvider(new BouncyCastleProvider());
Log.d(TAG, "/csrattrs:");
/*
byte[] octets = new byte[octetBuffer.remaining()];
octetBuffer.duplicate().get(octets);
for (byte b : octets) {
System.out.printf("%02x ", b & 0xff);
}
*/
Collection<Asn1Object> csrs = Asn1Decoder.decode(octetBuffer);
for (Asn1Object asn1Object : csrs) {
Log.d(TAG, asn1Object.toString());
}
if (csrs.size() != 1) {
throw new IOException("Unexpected object count in CSR attributes response: " + csrs.size());
}
Asn1Object sequence = csrs.iterator().next();
if (sequence.getClass() != Asn1Constructed.class) {
throw new IOException("Unexpected CSR attribute container: " + sequence);
}
String keyAlgo = null;
Asn1Oid keyAlgoOID = null;
String sigAlgo = null;
String curveName = null;
Asn1Oid pubCrypto = null;
int keySize = -1;
Map<Asn1Oid, ASN1Encodable> idAttributes = new HashMap<>();
for (Asn1Object child : sequence.getChildren()) {
if (child.getTag() == Asn1Decoder.TAG_OID) {
Asn1Oid oid = (Asn1Oid) child;
OidMappings.SigEntry sigEntry = OidMappings.getSigEntry(oid);
if (sigEntry != null) {
sigAlgo = sigEntry.getSigAlgo();
keyAlgoOID = sigEntry.getKeyAlgo();
keyAlgo = OidMappings.getJCEName(keyAlgoOID);
} else if (oid.equals(OidMappings.sPkcs9AtChallengePassword)) {
byte[] tlsUnique = httpHandler.getTLSUnique();
if (tlsUnique != null) {
idAttributes.put(oid, new DERPrintableString(Base64.encodeToString(tlsUnique, Base64.DEFAULT)));
} else {
Log.w(TAG, "Cannot retrieve TLS unique channel binding");
}
}
} else if (child.getTag() == Asn1Decoder.TAG_SEQ) {
Asn1Oid oid = null;
Set<Asn1Oid> oidValues = new HashSet<>();
List<Asn1Object> values = new ArrayList<>();
for (Asn1Object attributeSeq : child.getChildren()) {
if (attributeSeq.getTag() == Asn1Decoder.TAG_OID) {
oid = (Asn1Oid) attributeSeq;
} else if (attributeSeq.getTag() == Asn1Decoder.TAG_SET) {
for (Asn1Object value : attributeSeq.getChildren()) {
if (value.getTag() == Asn1Decoder.TAG_OID) {
oidValues.add((Asn1Oid) value);
} else {
values.add(value);
}
}
}
}
if (oid == null) {
throw new IOException("Invalid attribute, no OID");
}
if (oid.equals(OidMappings.sExtensionRequest)) {
for (Asn1Oid subOid : oidValues) {
if (OidMappings.isIDAttribute(subOid)) {
if (subOid.equals(OidMappings.sMAC)) {
idAttributes.put(subOid, new DERIA5String(omadmAdapter.getMAC()));
} else if (subOid.equals(OidMappings.sIMEI)) {
idAttributes.put(subOid, new DERIA5String(omadmAdapter.getImei()));
} else if (subOid.equals(OidMappings.sMEID)) {
idAttributes.put(subOid, new DERBitString(omadmAdapter.getMeid()));
} else if (subOid.equals(OidMappings.sDevID)) {
idAttributes.put(subOid, new DERPrintableString(omadmAdapter.getDevID()));
}
}
}
} else if (OidMappings.getCryptoID(oid) != null) {
pubCrypto = oid;
if (!values.isEmpty()) {
for (Asn1Object value : values) {
if (value.getTag() == Asn1Decoder.TAG_INTEGER) {
keySize = (int) ((Asn1Integer) value).getValue();
}
}
}
if (oid.equals(OidMappings.sAlgo_EC)) {
if (oidValues.isEmpty()) {
throw new IOException("No ECC curve name provided");
}
for (Asn1Oid value : oidValues) {
curveName = OidMappings.getJCEName(value);
if (curveName != null) {
break;
}
}
if (curveName == null) {
throw new IOException("Found no ECC curve for " + oidValues);
}
}
}
}
}
if (keyAlgoOID == null) {
throw new IOException("No public key algorithm specified");
}
if (pubCrypto != null && !pubCrypto.equals(keyAlgoOID)) {
throw new IOException("Mismatching key algorithms");
}
if (keyAlgoOID.equals(OidMappings.sAlgo_RSA)) {
if (keySize < MinRSAKeySize) {
if (keySize >= 0) {
Log.i(TAG, "Upgrading suggested RSA key size from " + keySize + " to " + MinRSAKeySize);
}
keySize = MinRSAKeySize;
}
}
Log.d(TAG, String.format("pub key '%s', signature '%s', ECC curve '%s', id-atts %s", keyAlgo, sigAlgo, curveName, idAttributes));
/*
Ruckus:
SEQUENCE:
OID=1.2.840.113549.1.1.11 (algo_id_sha256WithRSAEncryption)
RFC-7030:
SEQUENCE:
OID=1.2.840.113549.1.9.7 (challengePassword)
SEQUENCE:
OID=1.2.840.10045.2.1 (algo_id_ecPublicKey)
SET:
OID=1.3.132.0.34 (secp384r1)
SEQUENCE:
OID=1.2.840.113549.1.9.14 (extensionRequest)
SET:
OID=1.3.6.1.1.1.1.22 (mac-address)
OID=1.2.840.10045.4.3.3 (eccdaWithSHA384)
1L, 3L, 6L, 1L, 1L, 1L, 1L, 22
*/
// ECC Does not appear to be supported currently
KeyPairGenerator kpg = KeyPairGenerator.getInstance(keyAlgo);
if (curveName != null) {
AlgorithmParameters algorithmParameters = AlgorithmParameters.getInstance(keyAlgo);
algorithmParameters.init(new ECNamedCurveGenParameterSpec(curveName));
kpg.initialize(algorithmParameters.getParameterSpec(ECNamedCurveGenParameterSpec.class));
} else {
kpg.initialize(keySize);
}
KeyPair kp = kpg.generateKeyPair();
X500Principal subject = new X500Principal("CN=Android, O=Google, C=US");
mClientKey = kp.getPrivate();
// !!! Map the idAttributes into an ASN1Set of values to pass to
// the PKCS10CertificationRequest - this code is using outdated BC classes and
// has *not* been tested.
ASN1Set attributes;
if (!idAttributes.isEmpty()) {
ASN1EncodableVector payload = new DEREncodableVector();
for (Map.Entry<Asn1Oid, ASN1Encodable> entry : idAttributes.entrySet()) {
DERObjectIdentifier type = new DERObjectIdentifier(entry.getKey().toOIDString());
ASN1Set values = new DERSet(entry.getValue());
Attribute attribute = new Attribute(type, values);
payload.add(attribute);
}
attributes = new DERSet(payload);
} else {
attributes = null;
}
return new PKCS10CertificationRequest(sigAlgo, subject, kp.getPublic(), attributes, mClientKey).getEncoded();
}
Aggregations