Java Code Examples for org.bouncycastle.asn1.DERUTF8String

The following examples show how to use org.bouncycastle.asn1.DERUTF8String. 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
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 2
private static void populateTextField(Attribute[] attrs, JTextField textField, ASN1ObjectIdentifier pkcs9Attr) {
	if (attrs != null) {
		for (Attribute attribute : attrs) {

			ASN1ObjectIdentifier attributeOid = attribute.getAttrType();

			if (attributeOid.equals(pkcs9Attr)) {
				ASN1Encodable challenge = attribute.getAttributeValues()[0];

				// data type can be one of IA5String or UTF8String
				if (challenge instanceof DERPrintableString) {
					textField.setText(((DERPrintableString) challenge).getString());
				} else if (challenge instanceof DERUTF8String) {
					textField.setText(((DERUTF8String) challenge).getString());
				}
				textField.setCaretPosition(0);
			}
		}
	}
}
 
Example 3
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 4
Source Project: InflatableDonkey   Source File: KeySet.java    License: MIT License 6 votes vote down vote up
ASN1Primitive toASN1Primitive(boolean includeChecksum) {

        DEROctetString checksumEncodable = includeChecksum
                ? new DEROctetString(checksum())
                : null;

        ASN1Integer flagsEncodable = flags.map(ASN1Integer::new)
                .orElse(null);

        ASN1EncodableVector vector = DER.vector(
                new DERUTF8String(name),
                DER.toSet(keys),
                DER.toSet(serviceKeyIDs),
                checksumEncodable,
                flagsEncodable,
                signatureInfo.orElse(null));

        DERSequence sequence = new DERSequence(vector);
        return DER.toApplicationSpecific(APPLICATION_TAG, sequence);
    }
 
Example 5
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 6
Source Project: xipki   Source File: CmpCaClient.java    License: Apache License 2.0 6 votes vote down vote up
public X509Certificate enrollCertViaCsr(String certprofile, CertificationRequest csr,
    boolean profileInUri) throws Exception {
  ProtectedPKIMessageBuilder builder = new ProtectedPKIMessageBuilder(
      PKIHeader.CMP_2000, requestorSubject, responderSubject);
  builder.setMessageTime(new Date());
  builder.setTransactionID(randomTransactionId());
  builder.setSenderNonce(randomSenderNonce());

  builder.addGeneralInfo(
      new InfoTypeAndValue(CMPObjectIdentifiers.it_implicitConfirm, DERNull.INSTANCE));
  String uri = null;
  if (profileInUri) {
    uri = caUri + "?certprofile=" + certprofile.toLowerCase();
  } else {
    builder.addGeneralInfo(
        new InfoTypeAndValue(CMPObjectIdentifiers.regInfo_utf8Pairs,
            new DERUTF8String("certprofile?" + certprofile + "%")));
  }
  builder.setBody(new PKIBody(PKIBody.TYPE_P10_CERT_REQ, csr));
  ProtectedPKIMessage request = build(builder);

  PKIMessage response = transmit(request, uri);
  return parseEnrollCertResult(response, PKIBody.TYPE_CERT_REP, 1)
          .values().iterator().next().getCert();
}
 
Example 7
Source Project: xipki   Source File: ProxyMessage.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ASN1Primitive toASN1Primitive() {
  ASN1EncodableVector vector = new ASN1EncodableVector();
  vector.add(new DERUTF8String(control.getLabel()));

  byte[] id = control.getId();
  if (id != null) {
    vector.add(new DERTaggedObject(0, new DEROctetString(id)));
  }

  Set<P11KeyUsage> usages = control.getUsages();
  if (CollectionUtil.isNotEmpty(usages)) {
    ASN1EncodableVector asn1Usages = new ASN1EncodableVector();
    for (P11KeyUsage usage : usages) {
      int value = usageToValueMap.get(usage);
      asn1Usages.add(new ASN1Enumerated(value));
    }
    vector.add(new DERTaggedObject(1, new DERSequence(asn1Usages)));
  }

  if (control.getExtractable() != null) {
    vector.add(new DERTaggedObject(2, ASN1Boolean.getInstance(control.getExtractable())));
  }

  return new DERSequence(vector);
}
 
Example 8
Source Project: xipki   Source File: ProxyMessage.java    License: Apache License 2.0 6 votes vote down vote up
private NewObjectControl(ASN1Sequence seq) throws BadAsn1ObjectException {
  final int size = seq.size();
  Args.min(size, "seq.size", 1);
  String label = DERUTF8String.getInstance(seq.getObjectAt(0)).getString();
  byte[] id = null;

  for (int i = 1; i < size; i++) {
    ASN1Encodable obj = seq.getObjectAt(i);
    if (obj instanceof ASN1TaggedObject) {
      continue;
    }

    ASN1TaggedObject tagObj = (ASN1TaggedObject) obj;
    int tagNo = tagObj.getTagNo();
    if (tagNo == 0) {
      id = DEROctetString.getInstance(tagObj.getObject()).getOctets();
    }
  }

  this.control = new P11NewKeyControl(id, label);
}
 
Example 9
Source Project: xipki   Source File: ProxyMessage.java    License: Apache License 2.0 6 votes vote down vote up
private IdentityId(ASN1Sequence seq) throws BadAsn1ObjectException {
  requireRange(seq, 2, 4);
  P11SlotIdentifier slotId =
      SlotIdentifier.getInstance(seq.getObjectAt(0)).getValue();
  P11ObjectIdentifier keyId =
      ObjectIdentifier.getInstance(seq.getObjectAt(1)).getValue();
  String publicKeyLabel = null;
  String certLabel = null;

  final int n = seq.size();
  for (int i = 2; i < n; i++) {
    ASN1Encodable asn1 = seq.getObjectAt(i);
    if (asn1 instanceof ASN1TaggedObject) {
      ASN1TaggedObject tagAsn1 = (ASN1TaggedObject) asn1;
      int tag = tagAsn1.getTagNo();
      if (tag == 1) {
        publicKeyLabel = DERUTF8String.getInstance(tagAsn1.getObject()).getString();
      } else if (tag == 2) {
        certLabel = DERUTF8String.getInstance(tagAsn1.getObject()).getString();
      }
    }

  }

  this.value = new P11IdentityId(slotId, keyId, publicKeyLabel, certLabel);
}
 
Example 10
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 11
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 12
Source Project: hadoop-ozone   Source File: CertificateSignRequest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * addOtherNameAsn1Object requires special handling since
 * Bouncy Castle does not support othername as string.
 * @param name
 * @return
 */
private ASN1Object addOtherNameAsn1Object(String name) {
  // Below oid is copied from this URL:
  // https://docs.microsoft.com/en-us/windows/win32/adschema/a-middlename
  final String otherNameOID = "2.16.840.1.113730.3.1.34";
  ASN1EncodableVector otherName = new ASN1EncodableVector();
  otherName.add(new ASN1ObjectIdentifier(otherNameOID));
  otherName.add(new DERTaggedObject(
      true, GeneralName.otherName, new DERUTF8String(name)));
  return new DERTaggedObject(
      false, 0, new DERSequence(otherName));
}
 
Example 13
private Certificate generateCertWithExtension() throws Exception {
    final KeyPair keyPair = createKeyPair();

    final JcaX509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(
            new X500Name("CN=Test commonName"),
            BigInteger.valueOf(123456789),
            new Date(System.currentTimeMillis() - 10000),
            new Date(System.currentTimeMillis() + 10000),
            new X500Name("CN=Test commonName"),
            keyPair.getPublic()
    );

    certificateBuilder.addExtension(BCStyle.C, false, new DERUTF8String("DE"));
    certificateBuilder.addExtension(BCStyle.O, false, new DERUTF8String("Test organization"));
    certificateBuilder.addExtension(BCStyle.OU, false, new DERUTF8String("Test Unit"));
    certificateBuilder.addExtension(BCStyle.T, false, new DERUTF8String("Test Title"));
    certificateBuilder.addExtension(BCStyle.L, false, new DERUTF8String("Test locality"));
    certificateBuilder.addExtension(BCStyle.ST, false, new DERUTF8String("Test state"));

    return getCertificate(keyPair, certificateBuilder);
}
 
Example 14
/**
 * Get UPN String.
 *
 * @param seq ASN1Sequence abstraction representing subject alternative name.
 * First element is the object identifier, second is the object itself.
 *
 * @return UPN string or null
 */
private String getUPNStringFromSequence(final ASN1Sequence seq) {
    if (seq != null) {
        // First in sequence is the object identifier, that we must check
        final DERObjectIdentifier id = DERObjectIdentifier.getInstance(seq.getObjectAt(0));
        if (id != null && UPN_OBJECTID.equals(id.getId())) {
            final ASN1TaggedObject obj = (ASN1TaggedObject) seq.getObjectAt(1);
            final DERUTF8String str = DERUTF8String.getInstance(obj.getObject());
            return str.getString();
        }
    }
    return null;
}
 
Example 15
@Override
public void parse(ASN1Primitive derObject) {
    if (derObject instanceof DERUTF8String) {
        DERUTF8String derUTF8String = (DERUTF8String) derObject;
        this.setValue(derUTF8String.getString());
    } else {
        this.setValue(derObject.toString());
    }
}
 
Example 16
/**
 * Parse UPN/otherName
 *
 * @param generalName otherName object
 * @return UPN as string
 */
public static String parseUPN(GeneralName generalName) {
	// OtherName ::= SEQUENCE {
	//    type-id OBJECT IDENTIFIER,
	//    value [0] EXPLICIT ANY DEFINED BY type-id }

	ASN1Sequence otherName = (ASN1Sequence) generalName.getName();
	ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) otherName.getObjectAt(0);

	if (UPN_OID.equals(oid.getId())) {
		DERTaggedObject derTaggedObject = (DERTaggedObject) otherName.getObjectAt(1);
		DERUTF8String upn = DERUTF8String.getInstance(derTaggedObject.getObject());
		return MessageFormat.format(res.getString("GeneralNameUtil.OtherGeneralName"), "UPN", upn.getString());
	}

	// fallback to generic handling
	ASN1Encodable value = otherName.getObjectAt(1);
	try {
		return MessageFormat.format(res.getString("GeneralNameUtil.OtherGeneralName"),
				ObjectIdUtil.toString(oid),
				HexUtil.getHexString(value.toASN1Primitive().getEncoded(ASN1Encoding.DER)));
	} catch (IOException e) {
		return MessageFormat.format(res.getString("GeneralNameUtil.OtherGeneralName"),
				ObjectIdUtil.toString(oid),
				"");
	}
}
 
Example 17
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 18
@Parameterized.Parameters
public static Collection<ASN1Encodable[]> data() {
    ArrayList<ASN1Encodable[]> result = new ArrayList<ASN1Encodable[]>();
    result.add(new ASN1Encodable[]{new DERBMPString(NATIONAL_DN_CYRILLIC)});
    result.add(new ASN1Encodable[]{new DERUTF8String(NATIONAL_DN_CYRILLIC)});
    result.add(new ASN1Encodable[]{new DERBMPString(NATIONAL_DN_ARABIC)});
    result.add(new ASN1Encodable[]{new DERUTF8String(NATIONAL_DN_ARABIC)});
    return result;
}
 
Example 19
/**
 * ETSI TS 101 733 V2.2.1 (2013-04)
 * 5.11.2 signer-location Attribute
 * The signer-location attribute specifies a mnemonic for an address associated with the signer at a particular
 * geographical (e.g. city) location. The mnemonic is registered in the country in which the signer is located and
 * is used in
 * the provision of the Public Telegram Service (according to Recommendation ITU-T F.1 [11]).
 * The signer-location attribute shall be a signed attribute.
 *
 * @param parameters
 * @param signedAttributes
 * @return
 */
private void addSignerLocation(final CAdESSignatureParameters parameters, final ASN1EncodableVector signedAttributes) {
	/*
	 * In PAdES, the role is in the signature dictionary
	 */
	if (padesUsage) {
		return;
	}

	final eu.europa.esig.dss.model.SignerLocation signerLocationParameter = parameters.bLevel().getSignerLocation();
	if (signerLocationParameter != null && !signerLocationParameter.isEmpty()) {

		final DERUTF8String country = signerLocationParameter.getCountry() == null ? null : new DERUTF8String(signerLocationParameter.getCountry());
		final DERUTF8String locality = signerLocationParameter.getLocality() == null ? null : new DERUTF8String(signerLocationParameter.getLocality());
		final ASN1EncodableVector postalAddress = new ASN1EncodableVector();
		final List<String> postalAddressParameter = signerLocationParameter.getPostalAddress();
		if (postalAddressParameter != null) {
			for (final String addressLine : postalAddressParameter) {
				postalAddress.add(new DERUTF8String(addressLine));
			}
		}
		final DERSequence derSequencePostalAddress = new DERSequence(postalAddress);
		final SignerLocation signerLocation = new SignerLocation(country, locality, derSequencePostalAddress);
		final DERSet attrValues = new DERSet(signerLocation);
		final Attribute attribute = new Attribute(id_aa_ets_signerLocation, attrValues);
		signedAttributes.add(attribute);
	}
}
 
Example 20
Source Project: InflatableDonkey   Source File: KeySet.java    License: MIT License 5 votes vote down vote up
public KeySet(ASN1Primitive primitive) {

        ASN1Primitive app = DER.asApplicationSpecific(APPLICATION_TAG, primitive);
        DERIterator i = DER.asSequence(app);

        name = DER.as(DERUTF8String.class, i)
                .getString();

        keys = DER.asSet(i, PrivateKey::new);

        serviceKeyIDs = DER.asSet(i, TypeData::new);

        Optional<byte[]> optionalChecksum = i.nextIf(DEROctetString.class)
                .map(ASN1OctetString::getOctets);

        flags = i.nextIf(ASN1Integer.class)
                .map(ASN1Integer::getValue)
                .map(BigInteger::intValue);

        signatureInfo = i.optional()
                .map(SignatureInfo::new);

        checksum = calculateChecksum();

        Optional<Boolean> match = optionalChecksum.map(c -> Arrays.equals(c, checksum));

        if (match.isPresent()) {
            if (match.get()) {
                logger.debug("** KeySet() - checksums match");
            } else {
                try {
                    logger.debug("** KeySet()  - checksums do not match in: {} constructed: {}",
                            Hex.toHexString(primitive.getEncoded()),
                            Hex.toHexString(toASN1Primitive(false).getEncoded()));
                } catch (IOException ex) {
                    logger.debug("** KeySet() - IOException: ", ex);
                }
            }
        }
    }
 
Example 21
Source Project: xipki   Source File: DemoCertprofile.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected boolean initExtraExtension(ExtensionType extn) throws CertprofileException {
  ASN1ObjectIdentifier extnId = extn.getType().toXiOid();
  if (id_demo_without_conf.equals(extnId)) {
    this.addExtraWithoutConf = true;
    return true;
  } else if (id_demo_with_conf.equals(extnId)) {
    Object customObj = extn.getCustom();
    if (customObj == null) {
      throw new CertprofileException("ExtensionType.custom is not specified");
    }

    if (!(customObj instanceof JSONObject)) {
      throw new CertprofileException("ExtensionType.custom is not configured correctly");
    }

    // we need to first serialize the configuration
    byte[] serializedConf = JSON.toJSONBytes(customObj);
    ExtnDemoWithConf conf = JSON.parseObject(serializedConf, ExtnDemoWithConf.class);

    List<String> list = conf.getTexts();
    DERUTF8String[] texts = new DERUTF8String[list.size()];
    for (int i = 0; i < list.size(); i++) {
      texts[i] = new DERUTF8String(list.get(i));
    }

    this.sequence = new DERSequence(texts);

    this.addExtraWithConf = true;
    return true;
  } else {
    return false;
  }
}
 
Example 22
Source Project: xipki   Source File: ProxyMessage.java    License: Apache License 2.0 5 votes vote down vote up
private NewKeyControl(ASN1Sequence seq) throws BadAsn1ObjectException {
  final int size = seq.size();
  Args.min(size, "seq.size", 1);
  String label = DERUTF8String.getInstance(seq.getObjectAt(0)).getString();

  Set<P11KeyUsage> usages = new HashSet<>();
  byte[] id = null;
  Boolean extractable = null;

  for (int i = 1; i < size; i++) {
    ASN1Encodable obj = seq.getObjectAt(i);
    if (!(obj instanceof ASN1TaggedObject)) {
      continue;
    }

    ASN1TaggedObject tagObj = (ASN1TaggedObject) obj;
    int tagNo = tagObj.getTagNo();
    if (tagNo == 0) {
      id = DEROctetString.getInstance(tagObj.getObject()).getOctets();
    } else if (tagNo == 1) {
      ASN1Sequence usageSeq = ASN1Sequence.getInstance(tagObj.getObject());
      final int usageSize = usageSeq.size();
      for (int j = 0; j < usageSize; j++) {
        ASN1Enumerated usageEnum = ASN1Enumerated.getInstance(usageSeq.getObjectAt(j));
        int enumValue = usageEnum.getValue().intValue();
        P11KeyUsage usage = valueToUsageMap.get(enumValue);
        if (usage == null) {
          throw new IllegalArgumentException("invalid usage " + enumValue);
        }
        usages.add(usage);
      }
    } else if (tagNo == 2) {
      extractable = ASN1Boolean.getInstance(tagObj.getObject()).isTrue();
    }
  }

  this.control = new P11NewKeyControl(id, label);
  this.control.setUsages(usages);
  this.control.setExtractable(extractable);
}
 
Example 23
Source Project: xipki   Source File: ProxyMessage.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ASN1Primitive toASN1Primitive() {
  ASN1EncodableVector vector = new ASN1EncodableVector();
  vector.add(new DERUTF8String(control.getLabel()));

  byte[] id = control.getId();
  if (id != null) {
    vector.add(new DERTaggedObject(0, new DEROctetString(id)));
  }

  return new DERSequence(vector);
}
 
Example 24
Source Project: xipki   Source File: ProxyMessage.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ASN1Primitive toASN1Primitive() {
  ASN1EncodableVector vec = new ASN1EncodableVector();
  vec.add(new DEROctetString(value.getId()));
  vec.add(new DERUTF8String(value.getLabel()));
  return new DERSequence(vec);
}
 
Example 25
Source Project: xipki   Source File: ProxyMessage.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ASN1Primitive toASN1Primitive() {
  ASN1EncodableVector vector = new ASN1EncodableVector();
  vector.add(new SlotIdentifier(slotId));
  vector.add(new DERUTF8String(objectLabel));
  return new DERSequence(vector);
}
 
Example 26
Source Project: xipki   Source File: ProxyMessage.java    License: Apache License 2.0 5 votes vote down vote up
private static String getUtf8String(ASN1Encodable object) throws BadAsn1ObjectException {
  try {
    return DERUTF8String.getInstance(object).getString();
  } catch (IllegalArgumentException ex) {
    throw new BadAsn1ObjectException("invalid object UTF8String: " + ex.getMessage(), ex);
  }
}
 
Example 27
Source Project: xipki   Source File: CaEnrollBenchmark.java    License: Apache License 2.0 5 votes vote down vote up
public PKIMessage nextCertRequest() throws IOException, CertificateException {
  if (maxRequests > 0) {
    int num = processedRequests.getAndAdd(1);
    if (num >= maxRequests) {
      return null;
    }
  }

  CertReqMsg[] certReqMsgs = new CertReqMsg[num];

  for (int i = 0; i < num; i++) {
    CertTemplateBuilder certTempBuilder = new CertTemplateBuilder();

    long thisIndex = index.getAndIncrement();
    certTempBuilder.setSubject(benchmarkEntry.getX500Name(thisIndex));

    SubjectPublicKeyInfo spki = benchmarkEntry.getSubjectPublicKeyInfo();
    certTempBuilder.setPublicKey(spki);
    CertTemplate certTemplate = certTempBuilder.build();
    CertRequest certRequest = new CertRequest(new ASN1Integer(i + 1), certTemplate, null);

    String utf8pairs = "certprofile?" + benchmarkEntry.getCertprofile() + "%";
    AttributeTypeAndValue certprofileInfo =
        new AttributeTypeAndValue(CMPObjectIdentifiers.regInfo_utf8Pairs,
            new DERUTF8String(utf8pairs));
    AttributeTypeAndValue[] atvs = new AttributeTypeAndValue[]{certprofileInfo};

    certReqMsgs[i] = new CertReqMsg(certRequest, RA_VERIFIED, atvs);
  }

  PKIHeaderBuilder builder = new PKIHeaderBuilder(
      PKIHeader.CMP_2000, conf.requestor(), conf.responder());
  builder.setMessageTime(new ASN1GeneralizedTime(new Date()));
  builder.setTransactionID(randomBytes(8));
  builder.setSenderNonce(randomBytes(8));
  builder.setGeneralInfo(IMPLICIT_CONFIRM);

  PKIBody body = new PKIBody(PKIBody.TYPE_CERT_REQ, new CertReqMessages(certReqMsgs));
  return new PKIMessage(builder.build(), body);
}
 
Example 28
@Override
public void parse(ASN1Primitive primitive) {
    if (primitive instanceof DLSequence) {
        DLSequence sequence = (DLSequence) primitive;
        ASN1Encodable asn1Encodable = sequence.getObjectAt(0);
        if (asn1Encodable instanceof DERTaggedObject) {
            DERTaggedObject derTaggedObject = (DERTaggedObject) asn1Encodable;
            ASN1Primitive object = derTaggedObject.getObject();
            if (object instanceof DEROctetString) {
                OctetString octetString = new OctetString();
                octetString.parse(object);
                this.issuerName = octetString.getValueUTF8();
            } else if (object instanceof DERSequence) {
                DERSequence sequence2 = (DERSequence) object;
                for (int i = 0; i < sequence2.size(); i++) {
                    ASN1Encodable obj = sequence2.getObjectAt(i);
                    if (obj instanceof DERSet) {
                        DERSet set = (DERSet) obj;
                        ASN1Encodable object2 = set.getObjectAt(0);
                        if (object2 instanceof DERSequence) {
                            DERSequence sequence3 = (DERSequence) object2;
                            ObjectIdentifier objectIdendifier = new ObjectIdentifier();
                            objectIdendifier.parse(sequence3.getObjectAt(0).toASN1Primitive());
                            String name = null;
                            ASN1Encodable object3 = sequence3.getObjectAt(1);
                            if (object3 instanceof DERPrintableString) {
                                name = ((DERPrintableString) object3).getString();
                            } else if (object3 instanceof DERUTF8String) {
                                name = ((DERUTF8String) object3).getString();
                            } else {
                                System.out.println(policyMessagesBundle.getString("error.not.recognized.object",object3.getClass(),object3.toString()));
                            }
                            if (this.issuerNames == null) {
                                this.issuerNames = new HashMap<ObjectIdentifier, String>();
                            }
                            this.issuerNames.put(objectIdendifier, name);
                        }
                    }
                }
            }
        }
    }
}
 
Example 29
Source Project: dss   Source File: CAdESSignature.java    License: GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public SignatureProductionPlace getSignatureProductionPlace() {
	Attribute signatureProductionPlaceAttr = getSignedAttribute(PKCSObjectIdentifiers.id_aa_ets_signerLocation);
	if (signatureProductionPlaceAttr == null) {
		return null;
	}

	final ASN1Encodable asn1Encodable = signatureProductionPlaceAttr.getAttrValues().getObjectAt(0);
	SignerLocation signerLocation = null;
	try {
		signerLocation = SignerLocation.getInstance(asn1Encodable);
	} catch (Exception e) {
		LOG.error(e.getMessage(), e);
	}
	if (signerLocation == null) {
		return null;
	}
	final SignatureProductionPlace signatureProductionPlace = new SignatureProductionPlace();
	final DirectoryString countryName = signerLocation.getCountry();
	if (countryName != null) {
		signatureProductionPlace.setCountryName(countryName.getString());
	}
	final DirectoryString localityName = signerLocation.getLocality();
	if (localityName != null) {
		signatureProductionPlace.setCity(localityName.getString());
	}
	final StringBuilder address = new StringBuilder();
	final ASN1Sequence seq = signerLocation.getPostalAddress();
	if (seq != null) {

		for (int ii = 0; ii < seq.size(); ii++) {

			if (seq.getObjectAt(ii) instanceof DEROctetString) {
				if (address.length() > 0) {
					address.append(" / ");
				}
				// TODO: getOctets returns an array
				address.append(new String(((DEROctetString) seq.getObjectAt(ii)).getOctets()));
			} else if (seq.getObjectAt(ii) instanceof DERUTF8String) {

				if (address.length() > 0) {
					address.append(" / ");
				}
				final DERUTF8String derutf8String = (DERUTF8String) seq.getObjectAt(ii);
				address.append(derutf8String.getString());
			}
		}
	}
	signatureProductionPlace.setStreetAddress(address.toString());
	// This property is not used in CAdES version of signature
	// signatureProductionPlace.setStateOrProvince(stateOrProvince);
	return signatureProductionPlace;
}
 
Example 30
/**
 * ETSI TS 101 733 V2.2.1 (2013-04)
 *
 * 5.10.3 content-hints Attribute
 * The content-hints attribute provides information on the innermost signed content of a multi-layer message where
 * one content is encapsulated in another.
 * The syntax of the content-hints attribute type of the ES is as defined in ESS (RFC 2634 [5]).
 * When used to indicate the precise format of the data to be presented to the user, the following rules apply:
 * • the contentType indicates the type of the associated content. It is an object identifier (i.e. a unique string
 * of
 * integers) assigned by an authority that defines the content type; and
 * • when the contentType is id-data the contentDescription shall define the presentation format; the
 * format may be defined by MIME types.
 * When the format of the content is defined by MIME types, the following rules apply:
 * • the contentType shall be id-data as defined in CMS (RFC 3852 [4]);
 * • the contentDescription shall be used to indicate the encoding of the data, in accordance with the rules
 * defined RFC 2045 [6]; see annex F for an example of structured contents and MIME.
 * NOTE 1: id-data OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) pkcs7(7) 1 }.
 * NOTE 2: contentDescription is optional in ESS (RFC 2634 [5]). It may be used to complement
 * contentTypes defined elsewhere; such definitions are outside the scope of the present document.
 *
 * @param parameters
 * @param signedAttributes
 * @return
 */
private void addContentHints(final CAdESSignatureParameters parameters, final ASN1EncodableVector signedAttributes) {
	if (Utils.isStringNotBlank(parameters.getContentHintsType())) {

		final ASN1ObjectIdentifier contentHintsType = new ASN1ObjectIdentifier(parameters.getContentHintsType());
		final String contentHintsDescriptionString = parameters.getContentHintsDescription();
		final DERUTF8String contentHintsDescription = Utils.isStringBlank(contentHintsDescriptionString) ? null
				: new DERUTF8String(contentHintsDescriptionString);
		// "text/plain";
		// "1.2.840.113549.1.7.1";

		final ContentHints contentHints = new ContentHints(contentHintsType, contentHintsDescription);
		final DERSet attrValues = new DERSet(contentHints);
		final Attribute attribute = new Attribute(id_aa_contentHint, attrValues);
		signedAttributes.add(attribute);
	}
}