Java Code Examples for org.bouncycastle.asn1.ASN1ObjectIdentifier

The following examples show how to use org.bouncycastle.asn1.ASN1ObjectIdentifier. 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
Source Project: xipki   Source File: P12Actions.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected Object execute0() throws Exception {
  P12KeyGenerator keyGen = new P12KeyGenerator();
  KeystoreGenerationParameters keyGenParams = getKeyGenParameters();
  P12KeyGenerationResult keypair;

  ASN1ObjectIdentifier curveOid = EdECConstants.getCurveOid(curveName);
  if (curveOid != null) {
    keypair = keyGen.generateEdECKeypair(curveOid, keyGenParams, subject);
  } else {
    curveOid = AlgorithmUtil.getCurveOidForCurveNameOrOid(curveName);
    keypair = new P12KeyGenerator().generateECKeypair(curveOid, keyGenParams, subject);
  }
  saveKey(keypair);

  return null;
}
 
Example 2
Source Project: signer   Source File: CertValues.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
  public Attribute getValue() throws SignerException {

  	List<org.bouncycastle.asn1.x509.Certificate> certificateValues = new ArrayList<org.bouncycastle.asn1.x509.Certificate>();
  	try {
  		
  		int chainSize = certificates.length -1;
   		  for (int i = 0; i < chainSize; i++ ){
  		  	    X509Certificate cert = (X509Certificate) certificates[i];
  		  	  byte data[] = cert.getEncoded();
  		  	  certificateValues.add(org.bouncycastle.asn1.x509.Certificate.getInstance(data));    		  	  
  		 }	 
  		  org.bouncycastle.asn1.x509.Certificate[] certValuesArray = new org.bouncycastle.asn1.x509.Certificate[certificateValues.size()];
	return new Attribute(new ASN1ObjectIdentifier(identifier), new DERSet(new DERSequence(certificateValues.toArray(certValuesArray))));
  	} catch (CertificateEncodingException e) {
  		throw new SignerException(e.getMessage());
}
  }
 
Example 3
Source Project: xipki   Source File: P11ContentSigner.java    License: Apache License 2.0 6 votes vote down vote up
SM2(P11CryptService cryptService, P11IdentityId identityId,
    AlgorithmIdentifier signatureAlgId, ASN1ObjectIdentifier curveOid, BigInteger pubPointX,
    BigInteger pubPointY) throws XiSecurityException, P11TokenException {
  super(cryptService, identityId, signatureAlgId);

  String algOid = signatureAlgId.getAlgorithm().getId();
  HashAlgo hashAlgo = sigAlgHashMap.get(algOid);
  if (hashAlgo == null) {
    throw new XiSecurityException("unsupported signature algorithm " + algOid);
  }

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

  long mech = hashMechMap.get(hashAlgo);
  if (slot.supportsMechanism(mech)) {
    this.mechanism = mech;
    this.z = null; // not required
    this.outputStream = new ByteArrayOutputStream();
  } else if (slot.supportsMechanism(PKCS11Constants.CKM_VENDOR_SM2)) {
    this.mechanism = PKCS11Constants.CKM_VENDOR_SM2;
    this.z = GMUtil.getSM2Z(curveOid, pubPointX, pubPointY);
    this.outputStream = new DigestOutputStream(hashAlgo.createDigest());
  } else {
    throw new XiSecurityException("unsupported signature algorithm " + algOid);
  }
}
 
Example 4
Source Project: xipki   Source File: IaikP11Slot.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected P11Identity generateECMontgomeryKeypair0(ASN1ObjectIdentifier curveId,
    P11NewKeyControl control) throws P11TokenException {
  long mech = PKCS11Constants.CKM_EC_MONTGOMERY_KEY_PAIR_GEN;
  assertMechanismSupported(mech);

  ECPrivateKey privateKey = new ECPrivateKey(KeyType.EC_MONTGOMERY);
  ECPublicKey publicKey = new ECPublicKey(KeyType.EC_MONTGOMERY);
  setKeyAttributes(control, publicKey, privateKey);
  byte[] encodedCurveId;
  try {
    encodedCurveId = curveId.getEncoded();
  } catch (IOException ex) {
    throw new P11TokenException(ex.getMessage(), ex);
  }
  publicKey.getEcdsaParams().setByteArrayValue(encodedCurveId);
  return generateKeyPair(mech, control.getId(), privateKey, publicKey);
}
 
Example 5
private void populate(PolicyQualifierInfo policyQualifierInfo) throws IOException {
	if (policyQualifierInfo == null) {
		jrbCps.setSelected(true);
	} else {
		ASN1ObjectIdentifier policyQualifierId = policyQualifierInfo.getPolicyQualifierId();

		if (policyQualifierId.equals(new ASN1ObjectIdentifier(PKIX_CPS_POINTER_QUALIFIER.oid()))) {
			jrbCps.setSelected(true);
			jtfCps.setText(((DERIA5String) policyQualifierInfo.getQualifier()).getString());
			jtfCps.setCaretPosition(0);
		} else if (policyQualifierId.equals(new ASN1ObjectIdentifier(PKIX_USER_NOTICE_QUALIFIER.oid()))) {
			jrbUserNotice.setSelected(true);

			ASN1Encodable userNoticeObj = policyQualifierInfo.getQualifier();

			UserNotice userNotice = UserNotice.getInstance(userNoticeObj);

			junUserNotice.setUserNotice(userNotice);
		} else {
			jrbCps.setSelected(true);
		}
	}
}
 
Example 6
Source Project: dss   Source File: CMSCRLSource.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
private void collectRevocationRefs(ASN1ObjectIdentifier revocationRefsAttribute, RevocationRefOrigin origin) {
	try {
		final ASN1Encodable attrValue = DSSASN1Utils.getAsn1Encodable(unsignedAttributes, revocationRefsAttribute);
		if (attrValue != null) {
			final ASN1Sequence revocationRefs = (ASN1Sequence) attrValue;
			for (int ii = 0; ii < revocationRefs.size(); ii++) {
				final CrlOcspRef crlOcspRef = CrlOcspRef.getInstance(revocationRefs.getObjectAt(ii));
				final CrlListID crlIds = crlOcspRef.getCrlids();
				if (crlIds != null) {
					for (final CrlValidatedID id : crlIds.getCrls()) {
						final CRLRef crlRef = new CRLRef(id);
						addRevocationReference(crlRef, origin);
					}
				}
			}
		}
	} catch (Exception e) {
		// When error in computing or in format, the algorithm just continues.
		LOG.warn(
				"An error occurred during extraction of revocation references from  signature unsigned properties. "
						+ "Revocations for origin {} were not stored",
				origin.toString(), e);
	}
}
 
Example 7
Source Project: xipki   Source File: EmulatorP11Slot.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected P11Identity generateECEdwardsKeypair0(ASN1ObjectIdentifier curveOid,
    P11NewKeyControl control) throws P11TokenException {
  assertMechanismSupported(PKCS11Constants.CKM_EC_EDWARDS_KEY_PAIR_GEN);

  KeyPair keypair;
  try {
    if (!EdECConstants.isEdwardsCurve(curveOid)) {
      throw new P11TokenException("unknown curve  " + curveOid.getId());
    }

    keypair = KeyUtil.generateEdECKeypair(curveOid, random);
  } catch (NoSuchAlgorithmException | NoSuchProviderException
      | InvalidAlgorithmParameterException ex) {
    throw new P11TokenException(ex.getMessage(), ex);
  }
  return saveP11Entity(keypair, control);
}
 
Example 8
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 Project: xipki   Source File: X509Util.java    License: Apache License 2.0 6 votes vote down vote up
private static AccessDescription createAccessDescription(String accessMethodAndLocation)
    throws BadInputException {
  Args.notNull(accessMethodAndLocation, "accessMethodAndLocation");
  ConfPairs pairs;
  try {
    pairs = new ConfPairs(accessMethodAndLocation);
  } catch (IllegalArgumentException ex) {
    throw new BadInputException("invalid accessMethodAndLocation " + accessMethodAndLocation);
  }

  Set<String> oids = pairs.names();
  if (oids == null || oids.size() != 1) {
    throw new BadInputException("invalid accessMethodAndLocation " + accessMethodAndLocation);
  }

  String accessMethodS = oids.iterator().next();
  String taggedValue = pairs.value(accessMethodS);
  ASN1ObjectIdentifier accessMethod = new ASN1ObjectIdentifier(accessMethodS);

  GeneralName location = createGeneralName(taggedValue);
  return new AccessDescription(accessMethod, location);
}
 
Example 10
/**
 * get the atsHash index for verification of the provided token.
 *
 * @param signerInformation
 * @param timestampToken
 * @return a re-built ats-hash-index
 */
public Attribute getVerifiedAtsHashIndex(SignerInformation signerInformation, TimestampToken timestampToken) {
	final AttributeTable unsignedAttributes = timestampToken.getUnsignedAttributes();
	ASN1ObjectIdentifier atsHashIndexVersionIdentifier = DSSASN1Utils.getAtsHashIndexVersionIdentifier(unsignedAttributes);
	ASN1Sequence atsHashIndex = DSSASN1Utils.getAtsHashIndexByVersion(unsignedAttributes, atsHashIndexVersionIdentifier);
	if (atsHashIndex == null) {
		LOG.warn("A valid atsHashIndex [oid: {}] has not been found for a timestamp with id {}",
				atsHashIndexVersionIdentifier, timestampToken.getDSSIdAsString());
	}
	
	final AlgorithmIdentifier derObjectAlgorithmIdentifier = getAlgorithmIdentifier(atsHashIndex);
	final ASN1Sequence certificatesHashIndex = getVerifiedCertificatesHashIndex(atsHashIndex);
	final ASN1Sequence crLsHashIndex = getVerifiedCRLsHashIndex(atsHashIndex);
	final ASN1Sequence verifiedAttributesHashIndex = getVerifiedUnsignedAttributesHashIndex(signerInformation, atsHashIndex, 
			atsHashIndexVersionIdentifier);
	return getComposedAtsHashIndex(derObjectAlgorithmIdentifier, certificatesHashIndex, crLsHashIndex, 
			verifiedAttributesHashIndex, atsHashIndexVersionIdentifier);
}
 
Example 11
Source Project: keystore-explorer   Source File: X509Ext.java    License: GNU General Public License v3.0 6 votes vote down vote up
private String getHoldInstructionCodeStringValue(byte[] value) throws IOException {
	// @formatter:off
	/* HoldInstructionCode ::= OBJECT IDENTIFER */
	// @formatter:on

	StringBuilder sb = new StringBuilder();

	ASN1ObjectIdentifier holdInstructionCode = ASN1ObjectIdentifier.getInstance(value);
	HoldInstructionCodeType holdInstructionCodeType =
			HoldInstructionCodeType.resolveOid(holdInstructionCode.getId());

	if (holdInstructionCodeType != null) {
		sb.append(holdInstructionCodeType.friendly());
	} else {
		// Unrecognised Hold Instruction Code
		sb.append(holdInstructionCode.getId());
	}
	sb.append(NEWLINE);

	return sb.toString();
}
 
Example 12
private void updateExtensionValue() {
	int selectedRow = jtExtensions.getSelectedRow();

	if (selectedRow == -1) {
		jepExtensionValue.setText("");
		jbAsn1.setEnabled(false);
	} else {
		String oid = ((ASN1ObjectIdentifier) jtExtensions.getValueAt(selectedRow, 2)).getId();
		byte[] value = extensions.getExtensionValue(oid);
		boolean criticality = (Boolean) jtExtensions.getValueAt(selectedRow, 0);

		X509Ext ext = new X509Ext(oid, value, criticality);

		try {
			jepExtensionValue.setText("<html><body>" + ext.getStringValue()
			.replace(X509Ext.INDENT.getIndentChar().toString(), "&nbsp;")
			.replace(X509Ext.NEWLINE, "<br/>") + "</body></html>");
		} catch (Exception e) {
			jepExtensionValue.setText("");
			DError.displayError(this, e);
		}
		jepExtensionValue.setCaretPosition(0);

		jbAsn1.setEnabled(true);
	}
}
 
Example 13
Source Project: xipki   Source File: KeypairGenControl.java    License: Apache License 2.0 6 votes vote down vote up
public DSAKeypairGenControl(int pLength, int qLength, ASN1ObjectIdentifier keyAlgorithmOid) {
  if (pLength < 1024 | pLength % 1024 != 0) {
    throw new IllegalArgumentException("invalid pLength " + pLength);
  }

  if (qLength == 0) {
    if (pLength < 2048) {
      qLength = 160;
    } else if (pLength < 3072) {
      qLength = 224;
    } else {
      qLength = 256;
    }
  }

  this.parameterSpec = DSAParameterCache.getDSAParameterSpec(pLength, qLength, null);
  this.keyAlgorithm = new AlgorithmIdentifier(
      (keyAlgorithmOid != null) ? keyAlgorithmOid : X9ObjectIdentifiers.id_dsa,
      new DSAParameter(parameterSpec.getP(), parameterSpec.getQ(), parameterSpec.getG()));
}
 
Example 14
Source Project: xipki   Source File: AlgorithmUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static ASN1ObjectIdentifier getHashAlg(String hashAlgName)
    throws NoSuchAlgorithmException {
  Args.notBlank(hashAlgName, "hashAlgName");
  HashAlgo hashAlgo = HashAlgo.getInstance(hashAlgName.toUpperCase());
  if (hashAlgo == null) {
    throw new NoSuchAlgorithmException("Unsupported hash algorithm " + hashAlgName);
  }
  return hashAlgo.getOid();
}
 
Example 15
Source Project: xipki   Source File: ExtensionsChecker.java    License: Apache License 2.0 5 votes vote down vote up
private void checkExtnAuthorizationTemplate(StringBuilder failureMsg,
    byte[] extensionValue, Extensions requestedExtns, ExtensionControl extControl) {
  AuthorizationTemplate conf = authorizationTemplate;
  if (conf == null) {
    checkConstantExtnValue(ObjectIdentifiers.Xipki.id_xipki_ext_authorizationTemplate,
        failureMsg, extensionValue, requestedExtns, extControl);

    byte[] expected = getExpectedExtValue(
        ObjectIdentifiers.Xipki.id_xipki_ext_authorizationTemplate, requestedExtns, extControl);
    if (!Arrays.equals(expected, extensionValue)) {
      addViolation(failureMsg, "extension values", hex(extensionValue),
          (expected == null) ? "not present" : hex(expected));
    }
    return;
  }

  ASN1Sequence seq = ASN1Sequence.getInstance(extensionValue);
  ASN1ObjectIdentifier type = ASN1ObjectIdentifier.getInstance(seq.getObjectAt(0));
  ASN1OctetString accessRights = DEROctetString.getInstance(seq.getObjectAt(1));
  if (!conf.getType().getOid().equals(type.getId())) {
    addViolation(failureMsg, "type", type.getId(), conf.getType());
  }

  byte[] isRights = accessRights.getOctets();
  if (!Arrays.equals(conf.getAccessRights().getValue(), isRights)) {
    addViolation(failureMsg, "accessRights",
        hex(isRights), hex(conf.getAccessRights().getValue()));
  }
}
 
Example 16
Source Project: xipki   Source File: XijsonCertprofile.java    License: Apache License 2.0 5 votes vote down vote up
private void initAuthorityKeyIdentifier(Set<ASN1ObjectIdentifier> extnIds,
    Map<String, ExtensionType> extensions) throws CertprofileException {
  ASN1ObjectIdentifier type = Extension.authorityKeyIdentifier;
  if (extensionControls.containsKey(type)) {
    extnIds.remove(type);
    AuthorityKeyIdentifier extConf = getExtension(type, extensions).getAuthorityKeyIdentifier();
    this.useIssuerAndSerialInAki = (extConf == null) ? false : extConf.isUseIssuerAndSerial();
  }
}
 
Example 17
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 18
Source Project: xipki   Source File: ProxyP11Slot.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected P11Identity generateECKeypair0(ASN1ObjectIdentifier curveId, P11NewKeyControl control)
    throws P11TokenException {
  ProxyMessage.GenECKeypairParams asn1 =
      new ProxyMessage.GenECKeypairParams(slotId, control, curveId);
  byte[] resp = module.send(P11ProxyConstants.ACTION_GEN_KEYPAIR_EC, asn1);
  return parseGenerateKeypairResult(resp);
}
 
Example 19
Source Project: netty-4.1.22   Source File: Digester.java    License: Apache License 2.0 5 votes vote down vote up
public static DigestCalculator sha256() {
    Digest digest = new SHA256Digest();

    // The OID for SHA-256: http://www.oid-info.com/get/2.16.840.1.101.3.4.2.1
    ASN1ObjectIdentifier oid = new ASN1ObjectIdentifier(
            "2.16.840.1.101.3.4.2.1").intern();
    AlgorithmIdentifier algId = new AlgorithmIdentifier(oid);

    return new Digester(digest, algId);
}
 
Example 20
Source Project: xipki   Source File: CmpControl.java    License: Apache License 2.0 5 votes vote down vote up
public boolean isRequestPbmMacPermitted(AlgorithmIdentifier pbmMac) {
  ASN1ObjectIdentifier macOid = pbmMac.getAlgorithm();
  for (ASN1ObjectIdentifier oid : requestPbmMacs) {
    if (oid.equals(macOid)) {
      return true;
    }
  }
  return false;
}
 
Example 21
Source Project: xipki   Source File: EdECConstants.java    License: Apache License 2.0 5 votes vote down vote up
public static int getKeyBitSize(ASN1ObjectIdentifier curveOid) {
  if (id_X25519.equals(curveOid)) {
    return 256;
  } else if (id_X448.equals(curveOid)) {
    return 448;
  } else if (id_ED25519.equals(curveOid)) {
    return 256;
  } else if (id_ED448.equals(curveOid)) {
    return 448;
  } else {
    return 0;
  }
}
 
Example 22
Source Project: fabric-chaincode-java   Source File: TestUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Function to create a certificate with dummy attributes
 *
 * @param attributeValue {String} value to be written to the identity attributes
 *                       section of the certificate
 * @return encodedCert {String} encoded certificate with re-written attributes
 */
public static String createCertWithIdentityAttributes(final String attributeValue) throws Exception {

    // Use existing certificate with attributes
    final byte[] decodedCert = Base64.getDecoder().decode(CERT_MULTIPLE_ATTRIBUTES);
    // Create a certificate holder and builder
    final X509CertificateHolder certHolder = new X509CertificateHolder(decodedCert);
    final X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(certHolder);

    // special OID used by Fabric to save attributes in x.509 certificates
    final String fabricCertOid = "1.2.3.4.5.6.7.8.1";
    // Write the new attribute value
    final byte[] extDataToWrite = attributeValue.getBytes();
    certBuilder.replaceExtension(new ASN1ObjectIdentifier(fabricCertOid), true, extDataToWrite);

    // Create a privateKey
    final KeyPairGenerator generator = KeyPairGenerator.getInstance("EC");
    generator.initialize(384);
    final KeyPair keyPair = generator.generateKeyPair();

    // Create and build the Content Signer
    final JcaContentSignerBuilder contentSignerBuilder = new JcaContentSignerBuilder("SHA256withECDSA");
    final ContentSigner contentSigner = contentSignerBuilder.build(keyPair.getPrivate());
    // Build the Certificate from the certificate builder
    final X509CertificateHolder builtCert = certBuilder.build(contentSigner);
    final X509Certificate certificate = (X509Certificate) CertificateFactory.getInstance("X509")
            .generateCertificate(new ByteArrayInputStream(builtCert.getEncoded()));
    final String encodedCert = Base64.getEncoder().encodeToString(certificate.getEncoded());
    return encodedCert;
}
 
Example 23
Source Project: xipki   Source File: RequestIssuer.java    License: Apache License 2.0 5 votes vote down vote up
public String hashAlgorithmOID() {
  if (hashAlgo != null) {
    return hashAlgo.getOid().getId();
  } else {
    final int start = from + 2;
    byte[] bytes = Arrays.copyOfRange(data, start, start + 2 + (0xFF & data[from + 3]));
    return ASN1ObjectIdentifier.getInstance(bytes).getId();
  }
}
 
Example 24
Source Project: xipki   Source File: XijsonCertprofile.java    License: Apache License 2.0 5 votes vote down vote up
private void initKeyUsage(Set<ASN1ObjectIdentifier> extnIds,
    Map<String, ExtensionType> extensions) throws CertprofileException {
  ASN1ObjectIdentifier type = Extension.keyUsage;
  if (extensionControls.containsKey(type)) {
    extnIds.remove(type);
    KeyUsage extConf = getExtension(type, extensions).getKeyUsage();
    if (extConf != null) {
      this.keyusages = extConf.toXiKeyUsageOptions();
    }
  }
}
 
Example 25
Source Project: jcifs-ng   Source File: NegTokenInit.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public byte[] toByteArray () {
    try {
        ASN1EncodableVector fields = new ASN1EncodableVector();
        ASN1ObjectIdentifier[] mechs = getMechanisms();
        if ( mechs != null ) {
            ASN1EncodableVector vector = new ASN1EncodableVector();
            for ( int i = 0; i < mechs.length; i++ ) {
                vector.add(mechs[ i ]);
            }
            fields.add(new DERTaggedObject(true, 0, new DERSequence(vector)));
        }
        int ctxFlags = getContextFlags();
        if ( ctxFlags != 0 ) {
            fields.add(new DERTaggedObject(true, 1, new DERBitString(ctxFlags)));
        }
        byte[] mechanismToken = getMechanismToken();
        if ( mechanismToken != null ) {
            fields.add(new DERTaggedObject(true, 2, new DEROctetString(mechanismToken)));
        }
        byte[] mechanismListMIC = getMechanismListMIC();
        if ( mechanismListMIC != null ) {
            fields.add(new DERTaggedObject(true, 3, new DEROctetString(mechanismListMIC)));
        }

        ASN1EncodableVector ev = new ASN1EncodableVector();
        ev.add(SPNEGO_OID);
        ev.add(new DERTaggedObject(true, 0, new DERSequence(fields)));
        ByteArrayOutputStream collector = new ByteArrayOutputStream();
        DEROutputStream der = new DEROutputStream(collector);
        DERApplicationSpecific derApplicationSpecific = new DERApplicationSpecific(0, ev);
        der.writeObject(derApplicationSpecific);
        return collector.toByteArray();
    }
    catch ( IOException ex ) {
        throw new IllegalStateException(ex.getMessage());
    }
}
 
Example 26
Source Project: xipki   Source File: ExtensionsConfCreatorDemo.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
  try {
    extensionsEeCompelx("extensions-ee-complex.json");
    extensionsSyntaxExt("extensions-syntax-ext.json",
        new ASN1ObjectIdentifier("1.2.3.6.1"), null);
    extensionsSyntaxExt("extensions-syntax-ext-implicit-tag.json",
        new ASN1ObjectIdentifier("1.2.3.6.2"), new Tag(1, false));
    extensionsSyntaxExt("extensions-syntax-ext-explicit-tag.json",
        new ASN1ObjectIdentifier("1.2.3.6.3"), new Tag(1, true));
    extensionsAppleWwdr("extensions-apple-wwdr.json");
    extensionsGmt0015("extensions-gmt0015.json");
  } catch (Exception ex) {
    ex.printStackTrace();
  }
}
 
Example 27
Source Project: xipki   Source File: P11ContentSigner.java    License: Apache License 2.0 5 votes vote down vote up
RSA(P11CryptService cryptService, P11IdentityId identityId,
    AlgorithmIdentifier signatureAlgId) throws XiSecurityException, P11TokenException {
  super(cryptService, identityId, signatureAlgId);

  ASN1ObjectIdentifier algOid = signatureAlgId.getAlgorithm();
  HashAlgo hashAlgo = sigAlgHashAlgMap.get(algOid);
  if (hashAlgo == null) {
    throw new XiSecurityException("unsupported signature algorithm " + algOid.getId());
  }

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

  long mech = hashAlgMechMap.get(hashAlgo).longValue();
  if (slot.supportsMechanism(mech)) {
    mechanism = mech;
  } else if (slot.supportsMechanism(PKCS11Constants.CKM_RSA_PKCS)) {
    mechanism = PKCS11Constants.CKM_RSA_PKCS;
  } else if (slot.supportsMechanism(PKCS11Constants.CKM_RSA_X_509)) {
    mechanism = PKCS11Constants.CKM_RSA_X_509;
  } else {
    throw new XiSecurityException("unsupported signature algorithm " + algOid.getId());
  }

  if (mechanism == PKCS11Constants.CKM_RSA_PKCS || mechanism == PKCS11Constants.CKM_RSA_X_509) {
    this.digestPkcsPrefix = SignerUtil.getDigestPkcsPrefix(hashAlgo);
    this.outputStream = new DigestOutputStream(hashAlgo.createDigest());
  } else {
    this.digestPkcsPrefix = null;
    this.outputStream = new ByteArrayOutputStream();
  }

  RSAPublicKey rsaPubKey = (RSAPublicKey) cryptService.getIdentity(identityId).getPublicKey();
  this.modulusBitLen = rsaPubKey.getModulus().bitLength();
}
 
Example 28
Source Project: dss   Source File: CAdESSignature.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public String getContentType() {
	final Attribute contentTypeAttribute = getSignedAttribute(PKCSObjectIdentifiers.pkcs_9_at_contentType);
	if (contentTypeAttribute == null) {
		return null;
	}
	final ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) contentTypeAttribute.getAttrValues().getObjectAt(0);
	return oid.getId();
}
 
Example 29
private void addPressed() {
	Container container = getTopLevelAncestor();

	try {
		DObjectIdChooser dObjectIdChooser = null;

		if (container instanceof JDialog) {
			dObjectIdChooser = new DObjectIdChooser((JDialog) container, title, null);
		} else {
			dObjectIdChooser = new DObjectIdChooser((JFrame) container, title, null);
		}
		dObjectIdChooser.setLocationRelativeTo(container);
		dObjectIdChooser.setVisible(true);

		ASN1ObjectIdentifier newObjectId = dObjectIdChooser.getObjectId();

		if (newObjectId == null) {
			return;
		}

		objectIds.add(newObjectId);
		populate();
		selectCustomExtKeyUsageInTable(newObjectId);
	} catch (InvalidObjectIdException ex) {
		DError dError = null;

		if (container instanceof JDialog) {
			dError = new DError((JDialog) container, ex);
		} else {
			dError = new DError((JFrame) container, ex);
		}

		dError.setLocationRelativeTo(container);
		dError.setVisible(true);
	}
}
 
Example 30
Source Project: xipki   Source File: XijsonCertprofile.java    License: Apache License 2.0 5 votes vote down vote up
private void initPolicyConstraints(Set<ASN1ObjectIdentifier> extnIds,
    Map<String, ExtensionType> extensions) throws CertprofileException {
  ASN1ObjectIdentifier type = Extension.policyConstraints;
  if (extensionControls.containsKey(type)) {
    extnIds.remove(type);
    PolicyConstraints extConf = getExtension(type, extensions).getPolicyConstraints();
    if (extConf != null) {
      ASN1Sequence value = extConf.toXiPolicyConstrains();
      this.policyConstraints =
          new ExtensionValue(extensionControls.get(type).isCritical(), value);
    }
  }
}