Java Code Examples for org.bouncycastle.asn1.ASN1ObjectIdentifier#getId()

The following examples show how to use org.bouncycastle.asn1.ASN1ObjectIdentifier#getId() . 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: X509ProfileType.java    From xipki with Apache License 2.0 6 votes vote down vote up
public Map<ASN1ObjectIdentifier, ExtensionControl> buildExtensionControls()
    throws CertprofileException {
  // Extension controls
  Map<ASN1ObjectIdentifier, ExtensionControl> controls = new HashMap<>();
  for (ExtensionType extn : getExtensions()) {
    ASN1ObjectIdentifier oid = extn.getType().toXiOid();
    if (controls.containsKey(oid)) {
      throw new CertprofileException("duplicated definition of extension " + oid.getId());
    }

    boolean permittedInReq = extn.isPermittedInRequest();
    if (permittedInReq && extn.getConstant() != null) {
      throw new CertprofileException("constant Extension is not permitted in request");
    }

    if (!permittedInReq && extn.getSyntax() != null) {
      throw new CertprofileException("Extension with syntax must be permitted in request");
    }

    ExtensionControl ctrl = new ExtensionControl(extn.isCritical(), extn.isRequired(),
        permittedInReq);
    controls.put(oid, ctrl);
  }

  return Collections.unmodifiableMap(controls);
}
 
Example 2
Source File: P11ContentSigner.java    From xipki with Apache License 2.0 6 votes vote down vote up
EdDSA(P11CryptService cryptService, P11IdentityId identityId,
    AlgorithmIdentifier signatureAlgId)
    throws XiSecurityException, P11TokenException {
  super(cryptService, identityId, signatureAlgId);

  ASN1ObjectIdentifier algOid = signatureAlgId.getAlgorithm();
  if (!EdECConstants.id_ED25519.equals(algOid)) {
    throw new XiSecurityException("unsupproted signature algorithm " + algOid.getId());
  }

  mechanism = PKCS11Constants.CKM_EDDSA;

  P11Slot slot = cryptService.getSlot(identityId.getSlotId());
  if (slot.supportsMechanism(mechanism)) {
    throw new XiSecurityException("unsupported signature algorithm " + algOid.getId());
  }

  this.outputStream = new ByteArrayOutputStream();
}
 
Example 3
Source File: IdentifiedCertprofile.java    From xipki with Apache License 2.0 6 votes vote down vote up
private static void addExtension(ExtensionValues values, ASN1ObjectIdentifier extType,
    ASN1Encodable extValue, ExtensionControl extControl,
    Set<ASN1ObjectIdentifier> neededExtensionTypes,
    Set<ASN1ObjectIdentifier> wantedExtensionTypes) throws CertprofileException {
  if (extValue != null) {
    values.addExtension(extType, extControl.isCritical(), extValue);
    neededExtensionTypes.remove(extType);
    wantedExtensionTypes.remove(extType);
  } else if (extControl.isRequired()) {
    String description = ObjectIdentifiers.getName(extType);
    if (description == null) {
      description = extType.getId();
    }
    throw new CertprofileException("could not add required extension " + description);
  }
}
 
Example 4
Source File: AlgorithmUtil.java    From xipki with Apache License 2.0 6 votes vote down vote up
public static String getSignatureAlgoName(AlgorithmIdentifier sigAlgId)
    throws NoSuchAlgorithmException {
  ASN1ObjectIdentifier algOid = Args.notNull(sigAlgId, "sigAlgId").getAlgorithm();
  String name = null;
  if (PKCSObjectIdentifiers.id_RSASSA_PSS.equals(algOid)) {
    RSASSAPSSparams param = RSASSAPSSparams.getInstance(sigAlgId.getParameters());
    ASN1ObjectIdentifier digestAlgOid = param.getHashAlgorithm().getAlgorithm();
    name = digestOidToMgf1SigNameMap.get(digestAlgOid);
    if (name == null) {
      throw new NoSuchAlgorithmException("unsupported digest algorithm " + digestAlgOid);
    }
  } else {
    name = sigAlgOidToNameMap.get(algOid);
  }

  if (name == null) {
    throw new NoSuchAlgorithmException("unsupported signature algorithm " + algOid.getId());
  }
  return name;
}
 
Example 5
Source File: AlgorithmUtil.java    From xipki with Apache License 2.0 6 votes vote down vote up
public static AlgorithmCode getSigOrMacAlgoCode(AlgorithmIdentifier algId)
    throws NoSuchAlgorithmException {
  ASN1ObjectIdentifier oid = algId.getAlgorithm();
  AlgorithmCode code = algOidToCodeMap.get(oid);
  if (code != null) {
    return code;
  }

  if (PKCSObjectIdentifiers.id_RSASSA_PSS.equals(oid)) {
    RSASSAPSSparams param = RSASSAPSSparams.getInstance(algId.getParameters());
    ASN1ObjectIdentifier digestAlgOid = param.getHashAlgorithm().getAlgorithm();
    code = digestToMgf1AlgCodeMap.get(digestAlgOid);
    if (code == null) {
      throw new NoSuchAlgorithmException("unsupported digest algorithm " + digestAlgOid);
    }
    return code;
  } else {
    throw new NoSuchAlgorithmException("unsupported signature algorithm " + oid.getId());
  }
}
 
Example 6
Source File: ScepUtil.java    From xipki with Apache License 2.0 5 votes vote down vote up
public static ASN1ObjectIdentifier extractDigesetAlgorithmIdentifier(String sigOid,
    byte[] sigParams) throws NoSuchAlgorithmException {
  Args.notBlank(sigOid, "sigOid");

  ASN1ObjectIdentifier algOid = new ASN1ObjectIdentifier(sigOid);

  ASN1ObjectIdentifier digestAlgOid;
  if (PKCSObjectIdentifiers.md5WithRSAEncryption.equals(algOid)) {
    digestAlgOid = PKCSObjectIdentifiers.md5;
  } else if (PKCSObjectIdentifiers.sha1WithRSAEncryption.equals(algOid)) {
    digestAlgOid = X509ObjectIdentifiers.id_SHA1;
  } else if (PKCSObjectIdentifiers.sha224WithRSAEncryption.equals(algOid)) {
    digestAlgOid = NISTObjectIdentifiers.id_sha224;
  } else if (PKCSObjectIdentifiers.sha256WithRSAEncryption.equals(algOid)) {
    digestAlgOid = NISTObjectIdentifiers.id_sha256;
  } else if (PKCSObjectIdentifiers.sha384WithRSAEncryption.equals(algOid)) {
    digestAlgOid = NISTObjectIdentifiers.id_sha384;
  } else if (PKCSObjectIdentifiers.sha512WithRSAEncryption.equals(algOid)) {
    digestAlgOid = NISTObjectIdentifiers.id_sha512;
  } else if (PKCSObjectIdentifiers.id_RSASSA_PSS.equals(algOid)) {
    RSASSAPSSparams param = RSASSAPSSparams.getInstance(sigParams);
    digestAlgOid = param.getHashAlgorithm().getAlgorithm();
  } else {
    throw new NoSuchAlgorithmException("unknown signature algorithm" + algOid.getId());
  }

  return digestAlgOid;
}
 
Example 7
Source File: IdentifiedCertprofile.java    From xipki with Apache License 2.0 5 votes vote down vote up
private static ASN1Sequence createSubjectInfoAccess(
    Map<ASN1ObjectIdentifier, Extension> requestedExtensions,
    Map<ASN1ObjectIdentifier, Set<GeneralNameMode>> modes) throws BadCertTemplateException {
  if (modes == null) {
    return null;
  }

  Extension extn = requestedExtensions.get(Extension.subjectInfoAccess);
  if (extn == null) {
    return null;
  }

  ASN1Encodable extValue = extn.getParsedValue();
  if (extValue == null) {
    return null;
  }

  ASN1Sequence reqSeq = ASN1Sequence.getInstance(extValue);
  int size = reqSeq.size();

  ASN1EncodableVector vec = new ASN1EncodableVector();
  for (int i = 0; i < size; i++) {
    AccessDescription ad = AccessDescription.getInstance(reqSeq.getObjectAt(i));
    ASN1ObjectIdentifier accessMethod = ad.getAccessMethod();
    Set<GeneralNameMode> generalNameModes = modes.get(accessMethod);

    if (generalNameModes == null) {
      throw new BadCertTemplateException("subjectInfoAccess.accessMethod "
          + accessMethod.getId() + " is not allowed");
    }

    GeneralName accessLocation = BaseCertprofile.createGeneralName(
        ad.getAccessLocation(), generalNameModes);
    vec.add(new AccessDescription(accessMethod, accessLocation));
  } // end for

  return vec.size() > 0 ? new DERSequence(vec) : null;
}
 
Example 8
Source File: AlgorithmUtil.java    From xipki with Apache License 2.0 5 votes vote down vote up
public static int getHashOutputSizeInOctets(ASN1ObjectIdentifier hashAlgo)
    throws NoSuchAlgorithmException {
  Args.notNull(hashAlgo, "hashAlgo");
  HashAlgo hashAlgoType = HashAlgo.getInstance(hashAlgo);
  if (hashAlgoType == null) {
    throw new NoSuchAlgorithmException("Unsupported hash algorithm " + hashAlgo.getId());
  }
  return hashAlgoType.getLength();
}
 
Example 9
Source File: ExtendedExtension.java    From xipki with Apache License 2.0 5 votes vote down vote up
public static ExtendedExtension getInstance(byte[] encoded, int from, int len)
    throws EncodingException {
  Header hdrExtn = OcspRequest.readHeader(encoded, from);
  Header hdrOid = OcspRequest.readHeader(encoded, hdrExtn.readerIndex);
  Header hdrNext = OcspRequest.readHeader(encoded, hdrOid.readerIndex + hdrOid.len);
  Header hdrExtValue;

  boolean critical;
  if (hdrNext.tag == 0x01) { // critical
    critical = encoded[hdrNext.readerIndex] == (byte) 0xFF;
    hdrExtValue = OcspRequest.readHeader(encoded, hdrNext.readerIndex + hdrNext.len);
  } else {
    critical = false;
    hdrExtValue = hdrNext;
  }

  OID extnType = OID.getInstanceForEncoded(encoded, hdrOid.tagIndex);
  if (extnType == null) {
    byte[] bytes = new byte[hdrOid.readerIndex - hdrOid.tagIndex + hdrOid.len];
    System.arraycopy(encoded, hdrOid.tagIndex, bytes, 0, bytes.length);
    ASN1ObjectIdentifier oid = ASN1ObjectIdentifier.getInstance(bytes);
    LOG.warn("unknown extension {}", oid.getId());
    if (critical) {
      throw new EncodingException("unkown critical extension: " + oid.getId());
    } else {
      return null;
    }
  }

  int extnValueFrom = hdrExtValue.readerIndex;
  int extnValueLength = hdrExtValue.len;

  return new ExtendedExtension(extnType, encoded, from, critical, len,
      extnValueFrom, extnValueLength);
}
 
Example 10
Source File: ObjectIdUtil.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Get string representation of Object Identifier.
 *
 * @param objectIdentifer
 *            Object Identifier
 * @return String representation of Object Identifier
 */
public static String toString(ASN1ObjectIdentifier objectIdentifer) {
	String id = objectIdentifer.getId();
	String name = oidToNameMapping.get(id);

	if (name == null) {
		return id;
	}

	return MessageFormat.format("{0} ({1})", name, id);
}
 
Example 11
Source File: ObjectIdUtil.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Extract the arcs from an object identifier.
 *
 * @param oid
 *            Object identifier
 * @return Arcs
 * @throws InvalidObjectIdException
 *             If object identifier is not a '.' separated list of
 *             non-negative integers
 */
public static int[] extractArcs(ASN1ObjectIdentifier oid) throws InvalidObjectIdException {
	String oidStr = oid.getId();

	StringTokenizer strTokCnt = new StringTokenizer(oidStr, ".", false);
	int arcCount = strTokCnt.countTokens();

	StringTokenizer strTok = new StringTokenizer(oidStr, ".", true);

	boolean expectDelimiter = false;

	int[] arcs = new int[arcCount];
	int i = 0;
	while (strTok.hasMoreTokens()) {
		String token = strTok.nextToken();

		if (expectDelimiter && (!token.equals(".") || !strTok.hasMoreTokens())) {
			throw new InvalidObjectIdException(
					res.getString("InvalidOidNotNonNegativeIntSequence.exception.message"));
		} else if (!expectDelimiter) {
			try {
				arcs[i] = Integer.parseInt(token);

				if (arcs[i] < 0) {
					throw new InvalidObjectIdException(
							res.getString("InvalidOidNotNonNegativeIntSequence.exception.message"));
				}

				i++;
			} catch (NumberFormatException ex) {
				throw new InvalidObjectIdException(
						res.getString("InvalidOidNotNonNegativeIntSequence.exception.message"));
			}
		}

		expectDelimiter = !expectDelimiter;
	}

	return arcs;
}
 
Example 12
Source File: SubjectChecker.java    From xipki with Apache License 2.0 5 votes vote down vote up
private static ValidationIssue createSubjectIssue(ASN1ObjectIdentifier subjectAttrType) {
  ValidationIssue issue;
  String attrName = ObjectIdentifiers.getName(subjectAttrType);
  if (attrName == null) {
    attrName = subjectAttrType.getId().replace('.', '_');
    issue = new ValidationIssue("X509.SUBJECT." + attrName, "attribute "
        + subjectAttrType.getId());
  } else {
    issue = new ValidationIssue("X509.SUBJECT." + attrName, "attribute " + attrName
        + " (" + subjectAttrType.getId() + ")");
  }
  return issue;
}
 
Example 13
Source File: ExtensionsChecker.java    From xipki with Apache License 2.0 5 votes vote down vote up
private ValidationIssue createExtensionIssue(ASN1ObjectIdentifier extId) {
  String extName = ObjectIdentifiers.getName(extId);
  if (extName == null) {
    extName = extId.getId().replace('.', '_');
    return new ValidationIssue("X509.EXT." + extName, "extension " + extId.getId());
  } else {
    return new ValidationIssue("X509.EXT." + extName, "extension " + extName
        + " (" + extId.getId() + ")");
  }
}
 
Example 14
Source File: P12SignSpeed.java    From xipki with Apache License 2.0 4 votes vote down vote up
public EC(SecurityFactory securityFactory, String signatureAlgorithm, int threads,
    ASN1ObjectIdentifier curveOid) throws Exception {
  super(securityFactory, signatureAlgorithm, generateKeystore(curveOid),
      "PKCS#12 EC signature creation\ncurve: " + curveOid.getId(), threads);
}
 
Example 15
Source File: P12KeyGenSpeed.java    From xipki with Apache License 2.0 4 votes vote down vote up
public EC(ASN1ObjectIdentifier curveOid, SecurityFactory securityFactory) throws Exception {
  super("PKCS#12 EC key generation\ncurve: " + curveOid.getId(), securityFactory);
  this.curveOid = curveOid;
}
 
Example 16
Source File: Pkcs8Util.java    From keystore-explorer with GNU General Public License v3.0 4 votes vote down vote up
private static String getPrivateKeyAlgorithm(byte[] unencPkcs8) throws IOException, CryptoException {
	// @formatter:off
	/*
	 * Get private key algorithm from unencrypted PKCS #8 bytes:
	 *
	 * PrivateKeyInfo ::= ASN1Sequence {
	 * 		version Version,
	 * 		privateKeyAlgorithm PrivateKeyAlgorithmIdentifier, privateKey
	 * 		PrivateKey, attributes [0] IMPLICIT Attributes OPTIONAL
	 * }
	 *
	 * PrivateKeyAlgorithmIdentifier ::= AlgorithmIdentifier
	 *
	 * AlgorithmIdentifier ::= ASN1Sequence {
	 * 		algorithm OBJECT IDENTIFIER,
	 * 		parameters ANY DEFINED BY algorithm OPTIONAL
	 * }
	 */
	// @formatter:on

	try (ASN1InputStream ais = new ASN1InputStream(new ByteArrayInputStream(unencPkcs8))) {

		ASN1Encodable derEnc;
		try {
			derEnc = ais.readObject();
		} catch (OutOfMemoryError err) { // Happens with some non ASN.1 files
			throw new CryptoException(res.getString("NoUnencryptedPkcs8.exception.message"));
		}

		if (!(derEnc instanceof ASN1Sequence)) {
			throw new CryptoException(res.getString("NoUnencryptedPkcs8.exception.message"));
		}

		ASN1Sequence privateKeyInfoSequence = (ASN1Sequence) derEnc;

		derEnc = privateKeyInfoSequence.getObjectAt(1);

		if (!(derEnc instanceof ASN1Sequence)) {
			throw new CryptoException(res.getString("NoUnencryptedPkcs8.exception.message"));
		}

		ASN1Sequence privateKeyAlgorithmSequence = (ASN1Sequence) derEnc;

		derEnc = privateKeyAlgorithmSequence.getObjectAt(0);

		if (!(derEnc instanceof ASN1ObjectIdentifier)) {
			throw new CryptoException(res.getString("NoUnencryptedPkcs8.exception.message"));
		}

		ASN1ObjectIdentifier algorithmOid = (ASN1ObjectIdentifier) derEnc;

		String oid = algorithmOid.getId();

		if (oid.equals(RSA.oid())) {
			return RSA.jce();
		} else if (oid.equals(DSA.oid())) {
			return DSA.jce();
		} else {
			return oid; // Unknown algorithm
		}
	}
}
 
Example 17
Source File: ExtensionsChecker.java    From xipki with Apache License 2.0 4 votes vote down vote up
private static void checkAia(StringBuilder failureMsg, AuthorityInformationAccess aia,
    ASN1ObjectIdentifier accessMethod, Set<String> expectedUris) {
  String typeDesc;
  if (X509ObjectIdentifiers.id_ad_ocsp.equals(accessMethod)) {
    typeDesc = "OCSP";
  } else if (X509ObjectIdentifiers.id_ad_caIssuers.equals(accessMethod)) {
    typeDesc = "caIssuer";
  } else {
    typeDesc = accessMethod.getId();
  }

  List<AccessDescription> isAccessDescriptions = new LinkedList<>();
  for (AccessDescription accessDescription : aia.getAccessDescriptions()) {
    if (accessMethod.equals(accessDescription.getAccessMethod())) {
      isAccessDescriptions.add(accessDescription);
    }
  }

  int size = isAccessDescriptions.size();
  if (size != expectedUris.size()) {
    addViolation(failureMsg, "number of AIA " + typeDesc + " URIs", size, expectedUris.size());
    return;
  }

  Set<String> isUris = new HashSet<>();
  for (int i = 0; i < size; i++) {
    GeneralName isAccessLocation = isAccessDescriptions.get(i).getAccessLocation();
    if (isAccessLocation.getTagNo() != GeneralName.uniformResourceIdentifier) {
      addViolation(failureMsg, "tag of accessLocation of AIA ",
          isAccessLocation.getTagNo(), GeneralName.uniformResourceIdentifier);
    } else {
      String isOcspUri = ((ASN1String) isAccessLocation.getName()).getString();
      isUris.add(isOcspUri);
    }
  }

  Set<String> diffs = strInBnotInA(expectedUris, isUris);
  if (CollectionUtil.isNotEmpty(diffs)) {
    failureMsg.append(typeDesc).append(" URIs ").append(diffs);
    failureMsg.append(" are present but not expected; ");
  }

  diffs = strInBnotInA(isUris, expectedUris);
  if (CollectionUtil.isNotEmpty(diffs)) {
    failureMsg.append(typeDesc).append(" URIs ").append(diffs);
    failureMsg.append(" are absent but are required; ");
  }
}
 
Example 18
Source File: ObjectIdentifiers.java    From xipki with Apache License 2.0 4 votes vote down vote up
public static String oidToDisplayName(ASN1ObjectIdentifier type) {
  Args.notNull(type, "type");
  String name = getName(type);
  return (name == null) ? type.getId() : type.getId() + " (" + name + ")";
}
 
Example 19
Source File: P11ContentSigner.java    From xipki with Apache License 2.0 4 votes vote down vote up
RSAPSS(P11CryptService cryptService, P11IdentityId identityId,
    AlgorithmIdentifier signatureAlgId, SecureRandom random)
    throws XiSecurityException, P11TokenException {
  super(cryptService, identityId, signatureAlgId);
  Args.notNull(random, "random");

  ASN1ObjectIdentifier sigOid = signatureAlgId.getAlgorithm();
  if (!PKCSObjectIdentifiers.id_RSASSA_PSS.equals(sigOid)) {
    throw new XiSecurityException("unsupported signature algorithm "
        + signatureAlgId.getAlgorithm());
  }

  RSASSAPSSparams asn1Params = RSASSAPSSparams.getInstance(signatureAlgId.getParameters());
  ASN1ObjectIdentifier digestAlgOid = asn1Params.getHashAlgorithm().getAlgorithm();
  HashAlgo hashAlgo = HashAlgo.getInstance(digestAlgOid);
  if (hashAlgo == null) {
    throw new XiSecurityException("unsupported hash algorithm " + digestAlgOid.getId());
  }

  P11SlotIdentifier slotId = identityId.getSlotId();
  P11Slot slot = cryptService.getSlot(slotId);

  long mech = hashAlgMechMap.get(hashAlgo).longValue();
  if (slot.supportsMechanism(mech)) {
    this.mechanism = mech;
    this.parameters = new P11Params.P11RSAPkcsPssParams(asn1Params);
    this.outputStream = new ByteArrayOutputStream();
  } else if (slot.supportsMechanism(PKCS11Constants.CKM_RSA_PKCS_PSS)) {
    this.mechanism = PKCS11Constants.CKM_RSA_PKCS_PSS;
    this.parameters = new P11Params.P11RSAPkcsPssParams(asn1Params);
    this.outputStream = new DigestOutputStream(hashAlgo.createDigest());
  } else if (slot.supportsMechanism(PKCS11Constants.CKM_RSA_X_509)) {
    this.mechanism = PKCS11Constants.CKM_RSA_X_509;
    this.parameters = null;
    AsymmetricBlockCipher cipher = new P11PlainRSASigner();
    P11RSAKeyParameter keyParam;
    try {
      keyParam = P11RSAKeyParameter.getInstance(cryptService, identityId);
    } catch (InvalidKeyException ex) {
      throw new XiSecurityException(ex.getMessage(), ex);
    }
    PSSSigner pssSigner = SignerUtil.createPSSRSASigner(signatureAlgId, cipher);
    pssSigner.init(true, new ParametersWithRandom(keyParam, random));
    this.outputStream = new PSSSignerOutputStream(pssSigner);
  } else {
    throw new XiSecurityException("unsupported signature algorithm "
        + sigOid.getId() + " with " + hashAlgo);
  }
}
 
Example 20
Source File: CertificateService.java    From XS2A-Sandbox with Apache License 2.0 4 votes vote down vote up
RoleOfPspOid(ASN1ObjectIdentifier identifier) {
    super(identifier.getId());
}