Java Code Examples for org.bouncycastle.asn1.ASN1Sequence#getInstance()

The following examples show how to use org.bouncycastle.asn1.ASN1Sequence#getInstance() . 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: DSSASN1Utils.java    From dss with GNU Lesser General Public License v2.1 7 votes vote down vote up
public static Map<String, String> get(final X500Principal x500Principal) {
	Map<String, String> treeMap = new HashMap<>();
	final byte[] encoded = x500Principal.getEncoded();
	final ASN1Sequence asn1Sequence = ASN1Sequence.getInstance(encoded);
	final ASN1Encodable[] asn1Encodables = asn1Sequence.toArray();
	for (final ASN1Encodable asn1Encodable : asn1Encodables) {

		final DLSet dlSet = (DLSet) asn1Encodable;
		for (int ii = 0; ii < dlSet.size(); ii++) {

			final DLSequence dlSequence = (DLSequence) dlSet.getObjectAt(ii);
			if (dlSequence.size() != 2) {

				throw new DSSException("The DLSequence must contains exactly 2 elements.");
			}
			final ASN1Encodable asn1EncodableAttributeType = dlSequence.getObjectAt(0);
			final String stringAttributeType = getString(asn1EncodableAttributeType);
			final ASN1Encodable asn1EncodableAttributeValue = dlSequence.getObjectAt(1);
			final String stringAttributeValue = getString(asn1EncodableAttributeValue);
			treeMap.put(stringAttributeType, stringAttributeValue);
		}
	}
	return treeMap;
}
 
Example 2
Source File: ECDSASignatureProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static byte[] asn1derToConcatenatedRS(final byte[] derEncodedSignatureValue, int signLength) throws IOException {
    int len = signLength / 2;

    ASN1InputStream asn1InputStream = new ASN1InputStream(derEncodedSignatureValue);
    ASN1Primitive asn1Primitive = asn1InputStream.readObject();
    asn1InputStream.close();

    ASN1Sequence asn1Sequence = (ASN1Sequence.getInstance(asn1Primitive));
    ASN1Integer rASN1 = (ASN1Integer) asn1Sequence.getObjectAt(0);
    ASN1Integer sASN1 = (ASN1Integer) asn1Sequence.getObjectAt(1);
    X9IntegerConverter x9IntegerConverter = new X9IntegerConverter();
    byte[] r = x9IntegerConverter.integerToBytes(rASN1.getValue(), len);
    byte[] s = x9IntegerConverter.integerToBytes(sASN1.getValue(), len);

    byte[] concatenatedSignatureValue = new byte[signLength];
    System.arraycopy(r, 0, concatenatedSignatureValue, 0, len);
    System.arraycopy(s, 0, concatenatedSignatureValue, len, len);

    return concatenatedSignatureValue;
}
 
Example 3
Source File: CmpCaClient.java    From xipki with Apache License 2.0 6 votes vote down vote up
private Certificate[] cmpCaCerts() throws Exception {
  ProtectedPKIMessageBuilder builder = new ProtectedPKIMessageBuilder(
      PKIHeader.CMP_2000, requestorSubject, responderSubject);
  builder.setMessageTime(new Date());
  builder.setTransactionID(randomTransactionId());
  builder.setSenderNonce(randomSenderNonce());

  ASN1EncodableVector vec = new ASN1EncodableVector();
  vec.add(new ASN1Integer(CMP_ACTION_CACERTCHAIN));

  InfoTypeAndValue itv = new InfoTypeAndValue(id_xipki_cmp_cacertchain, new DERSequence(vec));
  PKIBody body = new PKIBody(PKIBody.TYPE_GEN_MSG, new GenMsgContent(itv));
  builder.setBody(body);

  ProtectedPKIMessage request = build(builder);
  PKIMessage response = transmit(request, null);
  ASN1Encodable asn1Value = extractGeneralRepContent(response, id_xipki_cmp_cacertchain.getId());
  ASN1Sequence seq = ASN1Sequence.getInstance(asn1Value);

  final int size = seq.size();
  Certificate[] caCerts = new Certificate[size];
  for (int i = 0; i < size; i++) {
    caCerts[i] = CMPCertificate.getInstance(seq.getObjectAt(i)).getX509v3PKCert();
  }
  return caCerts;
}
 
Example 4
Source File: DSSASN1Utils.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static List<String> getQCLegislations(CertificateToken certToken) {
	final List<String> result = new ArrayList<>();
	final byte[] qcStatement = certToken.getCertificate().getExtensionValue(Extension.qCStatements.getId());
	if (Utils.isArrayNotEmpty(qcStatement)) {
		try {
			final ASN1Sequence seq = getAsn1SequenceFromDerOctetString(qcStatement);
			// Sequence of QCStatement
			for (int ii = 0; ii < seq.size(); ii++) {
				final QCStatement statement = QCStatement.getInstance(seq.getObjectAt(ii));
				if (QC_LEGISLATION_OID.equals(statement.getStatementId().getId())) {
					ASN1Sequence sequenceLegislation = ASN1Sequence.getInstance(statement.getStatementInfo());
					for (int jj = 0; jj < sequenceLegislation.size(); jj++) {
						result.add(getString(sequenceLegislation.getObjectAt(jj)));
					}
					
				}
			}
		} catch (Exception e) {
			LOG.warn("Unable to parse the qCStatements extension '{}' : {}", Utils.toBase64(qcStatement), e.getMessage(), e);
		}
	}
	return result;
}
 
Example 5
Source File: X509Ext.java    From keystore-explorer with GNU General Public License v3.0 6 votes vote down vote up
private String getValidityModelStringValue(byte[] octets) {

		// @formatter:off

		/*
			ValidityModel::= SEQUENCE
			{
				validityModelId OBJECT IDENTIFIER
				validityModelInfo ANY DEFINED BY validityModelId OPTIONAL
			}
		 */

		// @formatter:on

		ASN1Sequence asn1Sequence = ASN1Sequence.getInstance(octets);
		ASN1ObjectIdentifier oid = ASN1ObjectIdentifier.getInstance(asn1Sequence.getObjectAt(0));
		ValidityModelType validityModel = ValidityModelType.resolveOid(oid.getId());

		return validityModel.friendly();
	}
 
Example 6
Source File: VersionParser.java    From ofdrw with Apache License 2.0 5 votes vote down vote up
/**
 * 解析电子签章数据版本
 *
 * @param o 带解析数据,可以是字节串也可以是ASN1对象
 * @return 带有版本的ASN1对象序列
 */
public static SESVersionHolder parseSES_SignatureVersion(Object o) {
    ASN1Sequence seq = ASN1Sequence.getInstance(o);
    SESVersion version;
    if (seq.size() >= 4 && seq.size() <= 5) {
        /*
         * GB/T 38540-2020 信息安全技术 安全电子签章密码技术规范
         *
         * - 签章信息
         * - 制章者证书
         * - 签名算法标识符
         * - 签名值
         * - [0] 对签名值的时间戳 【可选】
         */
        version = SESVersion.v4;
    } else if (seq.size() == 2) {
        /*
         * GM/T 0031-2014 安全电子签章密码技术规范 电子签章数据
         *
         * - 待电子签章数据
         * - 电子签章中签名值
         */
        version = SESVersion.v1;
    } else {
        throw new IllegalArgumentException("未知的数据结构,无法匹配任何已知版本电子签章数据。");
    }
    return new SESVersionHolder(version, seq);
}
 
Example 7
Source File: SignerUtil.java    From xipki with Apache License 2.0 5 votes vote down vote up
public static byte[] dsaSigX962ToPlain(byte[] x962Signature, int keyBitLen)
    throws XiSecurityException {
  Args.notNull(x962Signature, "x962Signature");
  ASN1Sequence seq = ASN1Sequence.getInstance(x962Signature);
  if (seq.size() != 2) {
    throw new IllegalArgumentException("invalid X962Signature");
  }
  BigInteger sigR = ASN1Integer.getInstance(seq.getObjectAt(0)).getPositiveValue();
  BigInteger sigS = ASN1Integer.getInstance(seq.getObjectAt(1)).getPositiveValue();
  return dsaSigToPlain(sigR, sigS, keyBitLen);
}
 
Example 8
Source File: DSSASN1Utils.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * This method extract the PSD2 QcStatement informations for a given certificate
 * 
 * @param certToken the certificate
 * @return an instance of {@code PSD2QcType} or null
 */
public static PSD2QcType getPSD2QcStatement(CertificateToken certToken) {
	PSD2QcType result = null;
	final byte[] qcStatement = certToken.getCertificate().getExtensionValue(Extension.qCStatements.getId());
	if (Utils.isArrayNotEmpty(qcStatement)) {
		try {
			final ASN1Sequence seq = getAsn1SequenceFromDerOctetString(qcStatement);
			for (int i = 0; i < seq.size(); i++) {
				final QCStatement statement = QCStatement.getInstance(seq.getObjectAt(i));
				if (OID.psd2_qcStatement.equals(statement.getStatementId())) {
					result = new PSD2QcType();
					ASN1Sequence psd2Seq = ASN1Sequence.getInstance(statement.getStatementInfo());
					ASN1Sequence rolesSeq = ASN1Sequence.getInstance(psd2Seq.getObjectAt(0));

					List<RoleOfPSP> rolesOfPSP = new ArrayList<>();
					for (int ii = 0; ii < rolesSeq.size(); ii++) {
						ASN1Sequence oneRoleSeq = ASN1Sequence.getInstance(rolesSeq.getObjectAt(ii));
						RoleOfPSP roleOfPSP = new RoleOfPSP();
						ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) oneRoleSeq.getObjectAt(0);
						roleOfPSP.setPspOid(RoleOfPspOid.fromOid(oid.getId()));
						roleOfPSP.setPspName(getString(oneRoleSeq.getObjectAt(1)));
						rolesOfPSP.add(roleOfPSP);
					}
					result.setRolesOfPSP(rolesOfPSP);
					result.setNcaName(getString(psd2Seq.getObjectAt(1)));
					result.setNcaId(getString(psd2Seq.getObjectAt(2)));
				}
			}
		} catch (Exception e) {
			LOG.warn("Unable to read QCStatement", e);
		}
	}
	return result;
}
 
Example 9
Source File: PolicyMapping.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Creates a new <code>PolicyMapping</code> instance.
 */
public static PolicyMapping getInstance(Object obj) {

	if (obj instanceof PolicyMapping) {
		return (PolicyMapping) obj;
	}
	if (obj != null) {
		return new PolicyMapping(ASN1Sequence.getInstance(obj));
	}

	return null;
}
 
Example 10
Source File: CRLDistributionPoints.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
public static CRLDistributionPoints getInstance(Object obj) {
	if (obj instanceof CRLDistributionPoints) {
		return (CRLDistributionPoints) obj;
	} else if (obj instanceof ASN1Sequence) {
		return new CRLDistributionPoints((ASN1Sequence) obj);
	} else if (obj instanceof byte[]) {
		return new CRLDistributionPoints(ASN1Sequence.getInstance(obj));
	}

	throw new IllegalArgumentException("unknown object type");
}
 
Example 11
Source File: SubjectInfoAccess.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
public static SubjectInfoAccess getInstance(Object obj) {
	if (obj instanceof SubjectInfoAccess) {
		return (SubjectInfoAccess) obj;
	} else if (obj instanceof ASN1Sequence) {
		return new SubjectInfoAccess((ASN1Sequence) obj);
	} else if (obj instanceof byte[]) {
		return new SubjectInfoAccess(ASN1Sequence.getInstance(obj));
	}

	throw new IllegalArgumentException("unknown object");
}
 
Example 12
Source File: CryptoDataLoader.java    From certificate-transparency-java with Apache License 2.0 5 votes vote down vote up
/**
 * Parses the beginning of a key, and determines the key algorithm (RSA or EC) based on the OID
 */
private static String determineKeyAlg(byte[] keyBytes) {
  ASN1Sequence seq = ASN1Sequence.getInstance(keyBytes);
  DLSequence seq1 = (DLSequence) seq.getObjects().nextElement();
  ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) seq1.getObjects().nextElement();
  if (PKCSObjectIdentifiers.rsaEncryption.equals(oid)) {
    return "RSA";
  } else if (X9ObjectIdentifiers.id_ecPublicKey.equals(oid)) {
    return "EC";
  } else {
    throw new IllegalArgumentException("Unsupported key type: " + oid);
  }
}
 
Example 13
Source File: ProxyP11Slot.java    From xipki with Apache License 2.0 5 votes vote down vote up
private ASN1Sequence requireSequence(byte[] response) throws P11TokenException {
  try {
    return ASN1Sequence.getInstance(response);
  } catch (IllegalArgumentException ex) {
    throw new P11TokenException("response is not ASN1Sequence", ex);
  }
}
 
Example 14
Source File: InfiniteLoopDSS621Test.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
private List<X509Certificate> extractCertificates(SignedData signedData) throws Exception {
	ASN1Set certificates = signedData.getCertificates();
	logger.debug("CERTIFICATES (" + certificates.size() + ") : " + certificates);

	List<X509Certificate> foundCertificates = new ArrayList<>();
	for (int i = 0; i < certificates.size(); i++) {
		ASN1Sequence seqCertif = ASN1Sequence.getInstance(certificates.getObjectAt(i));

		X509CertificateHolder certificateHolder = new X509CertificateHolder(seqCertif.getEncoded());
		CertificateToken certificate = DSSASN1Utils.getCertificate(certificateHolder);

		foundCertificates.add(certificate.getCertificate());
	}
	return foundCertificates;
}
 
Example 15
Source File: VersionParser.java    From ofdrw with Apache License 2.0 5 votes vote down vote up
/**
 * 解析电子印章版本
 *
 * @param o 带解析数据,可以是字节串也可以是ASN1对象
 * @return 带有版本的ASN1对象序列
 */
public static SESVersionHolder parseSES_SealVersion(Object o) {
    ASN1Sequence seq = ASN1Sequence.getInstance(o);
    SESVersion version;
    if (seq.size() == 4) {
        /*
         * GB/T 38540-2020 信息安全技术 安全电子签章密码技术规范 电子印章数据
         *
         * - 印章信息
         * - 制章者证书
         * - 签名算法标识符
         * - 签名值
         */
        version = SESVersion.v4;
    } else if (seq.size() == 2) {
        /*
         * GM/T 0031-2014 安全电子签章密码技术规范 电子印章数据
         *
         * - 印章信息
         * - 制章人对印章签名的信息
         */
        version = SESVersion.v1;
    } else {
        throw new IllegalArgumentException("未知的数据结构,无法匹配任何已知版本电子印章。");
    }
    return new SESVersionHolder(version, seq);
}
 
Example 16
Source File: X509Ext.java    From keystore-explorer with GNU General Public License v3.0 4 votes vote down vote up
private String getBiometricInfoStringValue(byte[] octets) {

		// @formatter:off

		/*
			BiometricSyntax ::= SEQUENCE OF BiometricData
			BiometricData ::= SEQUENCE
			{
				typeOfBiometricData TypeOfBiometricData,
				hashAlgorithm AlgorithmIdentifier,
				biometricDataHash OCTET STRING,
				sourceDataUri IA5String OPTIONAL
			}
			TypeOfBiometricData ::= CHOICE
			{
				predefinedBiometricType PredefinedBiometricType,
				biometricDataId OBJECT IDENTIIFER
			}
			PredefinedBiometricType ::= INTEGER
			{
				picture(0),
				handwritten-signature(1)
			}
		 */

		// @formatter:on

		StringBuilder sb = new StringBuilder();
		int biometricDataNr = 0;

		ASN1Sequence asn1Sequence = ASN1Sequence.getInstance(octets);

		for (ASN1Encodable asn1Encodable : asn1Sequence.toArray()) {
			BiometricData biometricData = BiometricData.getInstance(asn1Encodable);
			TypeOfBiometricData typeOfBiometricData = biometricData.getTypeOfBiometricData();
			AlgorithmIdentifier hashAlgorithm = biometricData.getHashAlgorithm();
			ASN1OctetString biometricDataHash = biometricData.getBiometricDataHash();
			DERIA5String sourceDataUri = biometricData.getSourceDataUri();

			sb.append(MessageFormat.format(res.getString("BiometricInfo.BiometricData"), biometricDataNr));
			sb.append(NEWLINE);

			sb.append(INDENT);
			if (typeOfBiometricData.isPredefined()) {
				int type = typeOfBiometricData.getPredefinedBiometricType();
				sb.append(MessageFormat.format(res.getString("BiometricInfo.TypeOfBiometricData"), type));
			} else {
				String biometricDataOid = typeOfBiometricData.getBiometricDataOid().getId();
				sb.append(MessageFormat.format(res.getString("BiometricInfo.TypeOfBiometricData"), biometricDataOid));
			}
			sb.append(NEWLINE);

			sb.append(INDENT);
			sb.append(MessageFormat.format(res.getString("BiometricInfo.HashAlgorithm"),
					hashAlgorithm.getAlgorithm().getId()));
			sb.append(NEWLINE);

			sb.append(INDENT);
			sb.append(MessageFormat.format(res.getString("BiometricInfo.BiometricDataHash"),
					HexUtil.getHexString(biometricDataHash.getOctets())));
			sb.append(NEWLINE);

			if (sourceDataUri != null) { // optional
				sb.append(INDENT);
				sb.append(MessageFormat.format(res.getString("BiometricInfo.SourceDataUri"), sourceDataUri.toString()));
				sb.append(NEWLINE);
			}
		}

		return sb.toString();
	}
 
Example 17
Source File: ExtensionsChecker.java    From xipki with Apache License 2.0 4 votes vote down vote up
private void checkExtnSubjectInfoAccess(StringBuilder failureMsg, byte[] extensionValue,
    Extensions requestedExtns, ExtensionControl extControl) {
  Map<ASN1ObjectIdentifier, Set<GeneralNameMode>> conf =
      certprofile.getSubjectInfoAccessModes();
  if (conf == null) {
    failureMsg.append("extension is present but not expected; ");
    return;
  }

  ASN1Encodable requestExtValue = null;
  if (requestedExtns != null) {
    requestExtValue = requestedExtns.getExtensionParsedValue(Extension.subjectInfoAccess);
  }
  if (requestExtValue == null) {
    failureMsg.append("extension is present but not expected; ");
    return;
  }

  ASN1Sequence requestSeq = ASN1Sequence.getInstance(requestExtValue);
  ASN1Sequence certSeq = ASN1Sequence.getInstance(extensionValue);

  int size = requestSeq.size();

  if (certSeq.size() != size) {
    addViolation(failureMsg, "size of GeneralNames", certSeq.size(), size);
    return;
  }

  for (int i = 0; i < size; i++) {
    AccessDescription ad = AccessDescription.getInstance(requestSeq.getObjectAt(i));
    ASN1ObjectIdentifier accessMethod = ad.getAccessMethod();
    Set<GeneralNameMode> generalNameModes = conf.get(accessMethod);

    if (generalNameModes == null) {
      failureMsg.append("accessMethod in requestedExtension ")
        .append(accessMethod.getId()).append(" is not allowed; ");
      continue;
    }

    AccessDescription certAccessDesc = AccessDescription.getInstance(
        certSeq.getObjectAt(i));
    ASN1ObjectIdentifier certAccessMethod = certAccessDesc.getAccessMethod();

    boolean bo = (accessMethod == null) ? (certAccessMethod == null)
        : accessMethod.equals(certAccessMethod);

    if (!bo) {
      addViolation(failureMsg, "accessMethod",
          (certAccessMethod == null) ? "null" : certAccessMethod.getId(),
          (accessMethod == null) ? "null" : accessMethod.getId());
      continue;
    }

    GeneralName accessLocation;
    try {
      accessLocation = createGeneralName(ad.getAccessLocation(), generalNameModes);
    } catch (BadCertTemplateException ex) {
      failureMsg.append("invalid requestedExtension: ").append(ex.getMessage()).append("; ");
      continue;
    }

    GeneralName certAccessLocation = certAccessDesc.getAccessLocation();
    if (!certAccessLocation.equals(accessLocation)) {
      failureMsg.append("accessLocation does not match the requested one; ");
    }
  }
}
 
Example 18
Source File: X509Ext.java    From keystore-explorer with GNU General Public License v3.0 4 votes vote down vote up
private String getSMIMECapabilitiesStringValue(byte[] octets) throws IOException {

		// @formatter:off

		/*
			SMIMECapabilities ::= SEQUENCE OF SMIMECapability

			SMIMECapability ::= SEQUENCE
			{
				capabilityID OBJECT IDENTIFIER,
				parameters ANY DEFINED BY capabilityID OPTIONAL
			}
		 */

		// @formatter:on

		StringBuilder sb = new StringBuilder();

		int capabilityNr = 0;

		ASN1Sequence asn1Sequence = ASN1Sequence.getInstance(octets);
		for (ASN1Encodable asn1Encodable : asn1Sequence.toArray()) {
			SMIMECapability capability = SMIMECapability.getInstance(asn1Encodable);
			ASN1ObjectIdentifier oid = capability.getCapabilityID();
			ASN1Encodable parameters = capability.getParameters();

			sb.append(MessageFormat.format(res.getString("SMIMECapability"), ++capabilityNr));
			sb.append(NEWLINE);

			sb.append(INDENT);
			sb.append(MessageFormat.format(res.getString("SMIMECapability.ObjectID"), ObjectIdUtil.toString(oid)));
			sb.append(NEWLINE);

			if (parameters != null) {
				sb.append(INDENT);
				sb.append(MessageFormat.format(res.getString("SMIMECapability.Parameter"),
						HexUtil.getHexString(parameters.toASN1Primitive().getEncoded())));
				sb.append(NEWLINE);
			}
		}

		return sb.toString();
	}
 
Example 19
Source File: CertGen.java    From snowblossom with Apache License 2.0 4 votes vote down vote up
/**
 * @param key_pair Key pair to use to sign the cert inner signed message, the node key
 * @param tls_wkp The temporary key to use just for this cert and TLS sessions
 * @param spec Address for 'key_pair'
 */
public static X509Certificate generateSelfSignedCert(WalletKeyPair key_pair, WalletKeyPair tls_wkp, AddressSpec spec)
  throws Exception
{

  AddressSpecHash address_hash = AddressUtil.getHashForSpec(spec);
  String address = AddressUtil.getAddressString(Globals.NODE_ADDRESS_STRING, address_hash);


  byte[] encoded_pub= tls_wkp.getPublicKey().toByteArray();
  SubjectPublicKeyInfo subjectPublicKeyInfo = new SubjectPublicKeyInfo(
    ASN1Sequence.getInstance(encoded_pub));

  String dn=String.format("CN=%s, O=Snowblossom", address);
  X500Name issuer = new X500Name(dn);
  BigInteger serial = BigInteger.valueOf(System.currentTimeMillis());
  Date notBefore = new Date(System.currentTimeMillis());
  Date notAfter = new Date(System.currentTimeMillis() + 86400000L * 365L * 10L);
  X500Name subject = issuer;

  X509v3CertificateBuilder cert_builder = new X509v3CertificateBuilder(
    issuer, serial, notBefore, notAfter, subject, subjectPublicKeyInfo);

  //System.out.println(org.bouncycastle.asn1.x509.Extension.subjectAlternativeName);
  ASN1ObjectIdentifier snow_claim_oid = new ASN1ObjectIdentifier("2.5.29.134");

  //System.out.println(spec);

  SignedMessagePayload payload = SignedMessagePayload.newBuilder().setTlsPublicKey(tls_wkp.getPublicKey()).build();
  SignedMessage sm = MsgSigUtil.signMessage(spec, key_pair, payload);

  byte[] sm_data = sm.toByteString().toByteArray();

  cert_builder.addExtension(snow_claim_oid, true, sm_data);

  String algorithm = "SHA256withRSA";

  AsymmetricKeyParameter privateKeyAsymKeyParam = PrivateKeyFactory.createKey(tls_wkp.getPrivateKey().toByteArray());

  AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(algorithm);
  AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);

  //ContentSigner sigGen = new BcECContentSignerBuilder(sigAlgId, digAlgId).build(privateKeyAsymKeyParam);
  ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(privateKeyAsymKeyParam);

  X509CertificateHolder certificateHolder = cert_builder.build(sigGen);

  X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certificateHolder);
  return cert;
}
 
Example 20
Source File: DSSASN1Utils.java    From dss with GNU Lesser General Public License v2.1 4 votes vote down vote up
public static String getUtf8String(final X500Principal x500Principal) {

		final byte[] encoded = x500Principal.getEncoded();
		final ASN1Sequence asn1Sequence = ASN1Sequence.getInstance(encoded);
		final ASN1Encodable[] asn1Encodables = asn1Sequence.toArray();
		final StringBuilder stringBuilder = new StringBuilder();
		/**
		 * RFC 4514 LDAP: Distinguished Names
		 * 2.1. Converting the RDNSequence
		 *
		 * If the RDNSequence is an empty sequence, the result is the empty or
		 * zero-length string.
		 *
		 * Otherwise, the output consists of the string encodings of each
		 * RelativeDistinguishedName in the RDNSequence (according to Section
		 * 2.2), starting with the last element of the sequence and moving
		 * backwards toward the first.
		 * ...
		 */
		for (int ii = asn1Encodables.length - 1; ii >= 0; ii--) {

			final ASN1Encodable asn1Encodable = asn1Encodables[ii];

			final DLSet dlSet = (DLSet) asn1Encodable;
			for (int jj = 0; jj < dlSet.size(); jj++) {

				final DLSequence dlSequence = (DLSequence) dlSet.getObjectAt(jj);
				if (dlSequence.size() != 2) {

					throw new DSSException("The DLSequence must contains exactly 2 elements.");
				}
				final ASN1Encodable attributeType = dlSequence.getObjectAt(0);
				final ASN1Encodable attributeValue = dlSequence.getObjectAt(1);
				String string = getString(attributeValue);

				/**
				 * RFC 4514 LDAP: Distinguished Names
				 * ...
				 * Other characters may be escaped.
				 *
				 * Each octet of the character to be escaped is replaced by a backslash
				 * and two hex digits, which form a single octet in the code of the
				 * character. Alternatively, if and only if the character to be escaped
				 * is one of
				 *
				 * ' ', '"', '#', '+', ',', ';', '<', '=', '>', or '\'
				 * (U+0020, U+0022, U+0023, U+002B, U+002C, U+003B,
				 * U+003C, U+003D, U+003E, U+005C, respectively)
				 *
				 * it can be prefixed by a backslash ('\' U+005C).
				 */
				string = Rdn.escapeValue(string);
				if (stringBuilder.length() != 0) {
					stringBuilder.append(',');
				}
				stringBuilder.append(attributeType).append('=').append(string);
			}
		}
		return stringBuilder.toString();
	}