org.bouncycastle.asn1.ASN1ObjectIdentifier Java Examples

The following examples show how to use org.bouncycastle.asn1.ASN1ObjectIdentifier. 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: CMSCRLSource.java    From dss with 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 #2
Source File: CertValues.java    From signer with 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 File: IaikP11Slot.java    From xipki with 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 #4
Source File: DPolicyQualifierInfoChooser.java    From keystore-explorer with GNU General Public License v3.0 6 votes vote down vote up
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 #5
Source File: P11ContentSigner.java    From xipki with 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 #6
Source File: EmulatorP11Slot.java    From xipki with 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 #7
Source File: DViewExtensions.java    From keystore-explorer with GNU General Public License v3.0 6 votes vote down vote up
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 #8
Source File: X509Ext.java    From keystore-explorer with 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 #9
Source File: CadesLevelBaselineLTATimestampExtractor.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * 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 #10
Source File: P12Actions.java    From xipki with 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 #11
Source File: KeypairGenControl.java    From xipki with 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 #12
Source File: X509Util.java    From xipki with 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 #13
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 #14
Source File: ProxyMessage.java    From xipki with Apache License 2.0 5 votes vote down vote up
private GenECEdwardsOrMontgomeryKeypairParams(ASN1Sequence seq) throws BadAsn1ObjectException {
  requireRange(seq, 3, 3);
  int idx = 0;
  slotId = SlotIdentifier.getInstance(seq.getObjectAt(idx++)).getValue();
  control = NewKeyControl.getInstance(seq.getObjectAt(idx++)).getControl();
  curveOid = ASN1ObjectIdentifier.getInstance(seq.getObjectAt(idx++));
}
 
Example #15
Source File: CertificateServiceImpl.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
private X509Certificate generateCertificate(String dn, KeyPair keyPair, int validity, String sigAlgName) throws GeneralSecurityException, IOException, OperatorCreationException {
    Provider bcProvider = new BouncyCastleProvider();
    Security.addProvider(bcProvider);

    // Use appropriate signature algorithm based on your keyPair algorithm.
    String signatureAlgorithm = sigAlgName;

    X500Name dnName = new X500Name(dn);
    Date from = new Date();
    Date to = new Date(from.getTime() + validity * 1000L * 24L * 60L * 60L);

    // Using the current timestamp as the certificate serial number
    BigInteger certSerialNumber = new BigInteger(Long.toString(from.getTime()));


    ContentSigner contentSigner = new JcaContentSignerBuilder(signatureAlgorithm).build(keyPair.getPrivate());
    JcaX509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(
            dnName, certSerialNumber, from, to, dnName, keyPair.getPublic());

    // true for CA, false for EndEntity
    BasicConstraints basicConstraints = new BasicConstraints(true);

    // Basic Constraints is usually marked as critical.
    certBuilder.addExtension(new ASN1ObjectIdentifier("2.5.29.19"), true, basicConstraints);

    return new JcaX509CertificateConverter().setProvider(bcProvider).getCertificate(certBuilder.build(contentSigner));
}
 
Example #16
Source File: Kerb5Context.java    From jcifs-ng with GNU Lesser General Public License v2.1 5 votes vote down vote up
Key searchSessionKey ( Subject subject ) throws GSSException {
    MIEName src = new MIEName(this.gssContext.getSrcName().export());
    MIEName targ = new MIEName(this.gssContext.getTargName().export());

    ASN1ObjectIdentifier mech = ASN1ObjectIdentifier.getInstance(this.gssContext.getMech().getDER());
    for ( KerberosTicket ticket : subject.getPrivateCredentials(KerberosTicket.class) ) {
        MIEName client = new MIEName(mech, ticket.getClient().getName());
        MIEName server = new MIEName(mech, ticket.getServer().getName());
        if ( src.equals(client) && targ.equals(server) ) {
            return ticket.getSessionKey();
        }
    }
    return null;
}
 
Example #17
Source File: NegTokenTarg.java    From jcifs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public byte[] toByteArray () {
    try {
        ByteArrayOutputStream collector = new ByteArrayOutputStream();
        DEROutputStream der = new DEROutputStream(collector);
        ASN1EncodableVector fields = new ASN1EncodableVector();
        int res = getResult();
        if ( res != UNSPECIFIED_RESULT ) {
            fields.add(new DERTaggedObject(true, 0, new ASN1Enumerated(res)));
        }
        ASN1ObjectIdentifier mech = getMechanism();
        if ( mech != null ) {
            fields.add(new DERTaggedObject(true, 1, mech));
        }
        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)));
        }
        der.writeObject(new DERTaggedObject(true, 1, new DERSequence(fields)));
        return collector.toByteArray();
    }
    catch ( IOException ex ) {
        throw new IllegalStateException(ex.getMessage());
    }
}
 
Example #18
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 #19
Source File: XijsonCertprofile.java    From xipki with 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 #20
Source File: ObjectIdComparator.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
@Override
public int compare(ASN1ObjectIdentifier oid1, ASN1ObjectIdentifier oid2) {
	int[] arcs1;
	int[] arcs2;

	try {
		arcs1 = ObjectIdUtil.extractArcs(oid1);
		arcs2 = ObjectIdUtil.extractArcs(oid2);
	} catch (InvalidObjectIdException ex) {
		throw new RuntimeException(ex);
	}

	for (int i = 0; ((i < arcs1.length) && (i < arcs2.length)); i++) {
		if (arcs1[i] > arcs2[i]) {
			return 1;
		} else if (arcs1[i] < arcs2[i]) {
			return -1;
		}
	}

	if (arcs2.length > arcs1.length) {
		for (int i = arcs1.length; i < arcs2.length; i++) {
			if (arcs2[i] != 0) {
				return -1;
			}
		}
	}

	if (arcs1.length > arcs2.length) {
		for (int i = arcs2.length; i < arcs1.length; i++) {
			if (arcs1[i] != 0) {
				return 1;
			}
		}
	}

	return 0;
}
 
Example #21
Source File: JCustomExtendedKeyUsage.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
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 #22
Source File: CAdESSignature.java    From dss with 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 #23
Source File: TestUtil.java    From fabric-chaincode-java with 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 #24
Source File: RequestIssuer.java    From xipki with 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 #25
Source File: XijsonCertprofile.java    From xipki with 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 #26
Source File: NegTokenInit.java    From jcifs-ng with 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 #27
Source File: DistinguishedNameValues.java    From fdroidclient with GNU General Public License v3.0 5 votes vote down vote up
public X509Principal getPrincipal() {
    Vector<ASN1ObjectIdentifier> oids = new Vector<ASN1ObjectIdentifier>();
    Vector<String> values = new Vector<String>();

    for (Map.Entry<ASN1ObjectIdentifier, String> entry : entrySet()) {
        if (entry.getValue() != null && !entry.getValue().equals("")) {
            oids.add(entry.getKey());
            values.add(entry.getValue());
        }
    }

    return new X509Principal(oids, values);
}
 
Example #28
Source File: ExtensionsConfCreatorDemo.java    From xipki with 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 #29
Source File: P11ContentSigner.java    From xipki with 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 #30
Source File: AlgorithmUtil.java    From xipki with 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();
}