org.bouncycastle.asn1.DERUTF8String Java Examples

The following examples show how to use org.bouncycastle.asn1.DERUTF8String. 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: ProxyMessage.java    From xipki with 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 #2
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 #3
Source File: CmpCaClient.java    From xipki with 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 #4
Source File: KeySet.java    From InflatableDonkey with 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 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: ProxyMessage.java    From xipki with 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 #7
Source File: ProxyMessage.java    From xipki with 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 #8
Source File: DialogHelper.java    From keystore-explorer with GNU General Public License v3.0 6 votes vote down vote up
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 #9
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 #10
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 #11
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 #12
Source File: ProxyMessage.java    From xipki with 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 #13
Source File: SslClientCertificateImplTest.java    From hivemq-community-edition with Apache License 2.0 5 votes vote down vote up
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
Source File: ProxyMessage.java    From xipki with 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 #15
Source File: ProxyMessage.java    From xipki with 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 #16
Source File: ProxyMessage.java    From xipki with 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 #17
Source File: ProxyMessage.java    From xipki with 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 #18
Source File: DemoCertprofile.java    From xipki with 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 #19
Source File: CaEnrollBenchmark.java    From xipki with 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 #20
Source File: CertificateSignRequest.java    From hadoop-ozone with 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 #21
Source File: X509SubjectAlternativeNameUPNPrincipalResolver.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
/**
 * 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 #22
Source File: FieldOfApplication.java    From signer with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void parse(ASN1Primitive derObject) {
    if (derObject instanceof DERUTF8String) {
        DERUTF8String derUTF8String = (DERUTF8String) derObject;
        this.setValue(derUTF8String.getString());
    } else {
        this.setValue(derObject.toString());
    }
}
 
Example #23
Source File: GeneralNameUtil.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 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 #24
Source File: KeySet.java    From InflatableDonkey with 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 #25
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 #26
Source File: CAdESLevelBaselineB.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * 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 #27
Source File: SignerSpecificTest.java    From xades4j with GNU Lesser General Public License v3.0 5 votes vote down vote up
@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 #28
Source File: UserIdentityExtractor.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public Object extractUserIdentity(X509Certificate[] certs) {
    if (certs == null || certs.length == 0) {
        throw new IllegalArgumentException();
    }

    try {
        Collection<List<?>> subjectAlternativeNames = certs[0].getSubjectAlternativeNames();

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

        Iterator<List<?>> iterator = subjectAlternativeNames.iterator();

        boolean foundUpn = false;
        String tempOtherName = null;
        String tempOid = null;

        while (iterator.hasNext() && !foundUpn) {
            List<?> next = iterator.next();

            if (Integer.class.cast(next.get(0)) == generalName) {

                // We will try to find UPN_OID among the subjectAltNames of type 'otherName' . Just if not found, we will fallback to the other type
                for (int i = 1 ; i<next.size() ; i++) {
                    Object obj = next.get(i);

                    // We have Subject Alternative Name of other type than 'otherName' . Just return it directly
                    if (generalName != 0) {
                        logger.tracef("Extracted identity '%s' from Subject Alternative Name of type '%d'", obj, generalName);
                        return obj;
                    }

                    byte[] otherNameBytes = (byte[]) obj;

                    try {
                        ASN1InputStream asn1Stream = new ASN1InputStream(new ByteArrayInputStream(otherNameBytes));
                        ASN1Encodable asn1otherName = asn1Stream.readObject();
                        asn1otherName = unwrap(asn1otherName);

                        ASN1Sequence asn1Sequence = ASN1Sequence.getInstance(asn1otherName);

                        if (asn1Sequence != null) {
                            ASN1Encodable encodedOid = asn1Sequence.getObjectAt(0);
                            ASN1ObjectIdentifier oid = ASN1ObjectIdentifier.getInstance(unwrap(encodedOid));
                            tempOid = oid.getId();

                            ASN1Encodable principalNameEncoded = asn1Sequence.getObjectAt(1);
                            DERUTF8String principalName = DERUTF8String.getInstance(unwrap(principalNameEncoded));

                            tempOtherName = principalName.getString();

                            // We found UPN among the 'otherName' principal. We don't need to look other
                            if (UPN_OID.equals(tempOid)) {
                                foundUpn = true;
                                break;
                            }
                        }

                    } catch (Exception e) {
                        logger.error("Failed to parse subjectAltName", e);
                    }
                }

            }
        }

        logger.tracef("Parsed otherName from subjectAltName. OID: '%s', Principal: '%s'", tempOid, tempOtherName);

        return tempOtherName;

    } catch (CertificateParsingException cause) {
        logger.errorf(cause, "Failed to obtain identity from subjectAltName extension");
    }

    return null;
}
 
Example #29
Source File: CmpUtil.java    From xipki with Apache License 2.0 4 votes vote down vote up
public static AttributeTypeAndValue buildAttributeTypeAndValue(CmpUtf8Pairs utf8Pairs) {
  Args.notNull(utf8Pairs, "utf8Pairs");
  return new AttributeTypeAndValue(CMPObjectIdentifiers.regInfo_utf8Pairs,
      new DERUTF8String(utf8Pairs.encoded()));
}
 
Example #30
Source File: ExtensionsChecker.java    From xipki with Apache License 2.0 4 votes vote down vote up
private void checkDirectoryString(ASN1ObjectIdentifier extnType,
    DirectoryStringType type, String text,
    StringBuilder failureMsg, byte[] extensionValue, Extensions requestedExtns,
    ExtensionControl extControl) {
  if (type == null) {
    checkConstantExtnValue(extnType, failureMsg, extensionValue, requestedExtns, extControl);
    return;
  }

  ASN1Primitive asn1;
  try {
    asn1 = ASN1Primitive.fromByteArray(extensionValue);
  } catch (IOException ex) {
    failureMsg.append("invalid syntax of extension value; ");
    return;
  }

  boolean correctStringType;

  switch (type) {
    case bmpString:
      correctStringType = (asn1 instanceof DERBMPString);
      break;
    case printableString:
      correctStringType = (asn1 instanceof DERPrintableString);
      break;
    case teletexString:
      correctStringType = (asn1 instanceof DERT61String);
      break;
    case utf8String:
      correctStringType = (asn1 instanceof DERUTF8String);
      break;
    default:
      throw new IllegalStateException("should not reach here, unknown DirectoryStringType "
          + type);
  } // end switch

  if (!correctStringType) {
    failureMsg.append("extension value is not of type DirectoryString.")
      .append(text).append("; ");
    return;
  }

  String extTextValue = ((ASN1String) asn1).getString();
  if (!text.equals(extTextValue)) {
    addViolation(failureMsg, "content", extTextValue, text);
  }
}