List of usage examples for org.bouncycastle.asn1 DERSequence getEncoded
public byte[] getEncoded() throws IOException
From source file:net.sf.keystore_explorer.crypto.publickey.KeyIdentifierGenerator.java
License:Open Source License
private byte[] encodeRsaPublicKeyAsBitString(RSAPublicKey rsaPublicKey) throws IOException { ASN1EncodableVector vec = new ASN1EncodableVector(); vec.add(new ASN1Integer(rsaPublicKey.getModulus())); vec.add(new ASN1Integer(rsaPublicKey.getPublicExponent())); DERSequence derSequence = new DERSequence(vec); return derSequence.getEncoded(); }
From source file:org.demoiselle.signer.policy.engine.asn1.etsi.CertificateTrustPoint.java
License:Open Source License
@Override public void parse(ASN1Primitive derObject) { ASN1Sequence derSequence = ASN1Object.getDERSequence(derObject); DERSequence x509Sequence = (DERSequence) derSequence.getObjectAt(0).toASN1Primitive(); try {/*www .j av a 2s . c o m*/ ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(x509Sequence.getEncoded()); this.trustpoint = (X509Certificate) CertificateFactory.getInstance("X509") .generateCertificate(byteArrayInputStream); } catch (Throwable error) { error.printStackTrace(); } int total = derSequence.size(); if (total > 0) { for (int i = 0; i < total; i++) { ASN1Primitive object = derSequence.getObjectAt(i).toASN1Primitive(); if (object instanceof DERTaggedObject) { DERTaggedObject derTaggedObject = (DERTaggedObject) object; TAG tag = TAG.getTag(derTaggedObject.getTagNo()); switch (tag) { case pathLenConstraint: this.pathLenConstraint = new PathLenConstraint(); this.pathLenConstraint.parse(object); break; case acceptablePolicySet: this.acceptablePolicySet = new AcceptablePolicySet(); this.acceptablePolicySet.parse(object); break; case nameConstraints: this.nameConstraints = new NameConstraints(); this.nameConstraints.parse(object); break; case policyConstraints: this.policyConstraints = new PolicyConstraints(); this.policyConstraints.parse(object); break; default: break; } } } } }
From source file:org.ejbca.extra.ra.ScepRequestGenerator.java
License:Open Source License
public byte[] generateGetCertInitial(String dn, X509Certificate ca) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException, CertStoreException, IOException, CMSException { this.cacert = ca; this.reqdn = dn; ASN1EncodableVector vec = new ASN1EncodableVector(); vec.add(new DERUTF8String(ca.getIssuerDN().getName())); vec.add(new DERUTF8String(dn)); DERSequence seq = new DERSequence(vec); // wrap message in pkcs#7 byte[] msg = wrap(seq.getEncoded(), "20"); return msg;//from ww w. j ava 2 s . c om }
From source file:org.kse.crypto.privatekey.OpenSslPvkUtil.java
License:Open Source License
/** * OpenSSL encode a private key.//from www.j a v a2 s. c om * * @return The encoding * @param privateKey * The private key * @throws CryptoException * Problem encountered while getting the encoded private key */ public static byte[] get(PrivateKey privateKey) throws CryptoException { // DER encoding for each key type is a sequence ASN1EncodableVector vec = new ASN1EncodableVector(); if (privateKey instanceof ECPrivateKey) { try { org.bouncycastle.asn1.sec.ECPrivateKey ecPrivateKey = org.bouncycastle.asn1.sec.ECPrivateKey .getInstance(privateKey.getEncoded()); return ecPrivateKey.toASN1Primitive().getEncoded(); } catch (IOException e) { throw new CryptoException(res.getString("NoDerEncodeOpenSslPrivateKey.exception.message"), e); } } else if (privateKey instanceof RSAPrivateCrtKey) { RSAPrivateCrtKey rsaPrivateKey = (RSAPrivateCrtKey) privateKey; vec.add(new ASN1Integer(VERSION)); vec.add(new ASN1Integer(rsaPrivateKey.getModulus())); vec.add(new ASN1Integer(rsaPrivateKey.getPublicExponent())); vec.add(new ASN1Integer(rsaPrivateKey.getPrivateExponent())); vec.add(new ASN1Integer(rsaPrivateKey.getPrimeP())); vec.add(new ASN1Integer(rsaPrivateKey.getPrimeQ())); vec.add(new ASN1Integer(rsaPrivateKey.getPrimeExponentP())); vec.add(new ASN1Integer(rsaPrivateKey.getPrimeExponentQ())); vec.add(new ASN1Integer(rsaPrivateKey.getCrtCoefficient())); } else { DSAPrivateKey dsaPrivateKey = (DSAPrivateKey) privateKey; DSAParams dsaParams = dsaPrivateKey.getParams(); BigInteger primeModulusP = dsaParams.getP(); BigInteger primeQ = dsaParams.getQ(); BigInteger generatorG = dsaParams.getG(); BigInteger secretExponentX = dsaPrivateKey.getX(); // Derive public key from private key parts, ie Y = G^X mod P BigInteger publicExponentY = generatorG.modPow(secretExponentX, primeModulusP); vec.add(new ASN1Integer(VERSION)); vec.add(new ASN1Integer(primeModulusP)); vec.add(new ASN1Integer(primeQ)); vec.add(new ASN1Integer(generatorG)); vec.add(new ASN1Integer(publicExponentY)); vec.add(new ASN1Integer(secretExponentX)); } DERSequence derSequence = new DERSequence(vec); try { return derSequence.getEncoded(); } catch (IOException ex) { throw new CryptoException(res.getString("NoDerEncodeOpenSslPrivateKey.exception.message"), ex); } }
From source file:org.metaeffekt.dcc.commons.pki.CertificateManager.java
License:Apache License
protected List<Extension> createExtensions(PublicKey publicKey, X509Certificate issuerCertificate) throws CertIOException, NoSuchAlgorithmException, IOException { List<Extension> extensions = new ArrayList<>(); String certType = getProperty(PROPERTY_CERT_TYPE, CERT_TYPE_TLS); // backward compatibility if (CERT_TYPE_CA_OLD.equals(certType)) { certType = CERT_TYPE_CA;//from ww w.j a va 2 s. c o m } // subject key identifier boolean criticalKeyIdentifier = getProperty(PROPERTY_CERT_CRITICAL_KEY_IDENTIFIER, false); extensions.add(new Extension(Extension.subjectKeyIdentifier, criticalKeyIdentifier, new JcaX509ExtensionUtils().createSubjectKeyIdentifier(publicKey).getEncoded())); // basic constraints if (CERT_TYPE_CA.equals(certType)) { boolean criticalCaConstraints = getProperty(PROPERTY_CERT_CRITICAL_CA, true); int chainLengthConstraint = getProperty(PROPERTY_CERT_CHAIN_LENGTH, 0); if (chainLengthConstraint > 0) { extensions.add(new Extension(Extension.basicConstraints, criticalCaConstraints, new BasicConstraints(chainLengthConstraint).getEncoded())); } else { extensions.add(new Extension(Extension.basicConstraints, criticalCaConstraints, new BasicConstraints(true).getEncoded())); } } // key usage int keyUsageInt = getKeyUsage(certType); if (keyUsageInt != 0) { // FIXME: test whether we can default to true here boolean criticalKeyUsage = getProperty(PROPERTY_CERT_CRITICAL_KEY_USAGE, false); KeyUsage keyUsage = new KeyUsage(keyUsageInt); extensions.add(new Extension(Extension.keyUsage, criticalKeyUsage, keyUsage.getEncoded())); } // extended key usage KeyPurposeId[] keyPurposeDefault = null; if (CERT_TYPE_TLS.equals(certType)) { // defaults for TLS keyPurposeDefault = new KeyPurposeId[] { KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_serverAuth }; } boolean criticalKeyPurpose = getProperty(PROPERTY_CERT_CRITICAL_KEY_PURPOSE, false); KeyPurposeId[] keyPurpose = createKeyPurposeIds(keyPurposeDefault); if (keyPurpose != null) { extensions.add(new Extension(Extension.extendedKeyUsage, criticalKeyPurpose, new ExtendedKeyUsage(keyPurpose).getEncoded())); } // subjectAlternativeName List<ASN1Encodable> subjectAlternativeNames = extractAlternativeNames(PROPERTY_PREFIX_CERT_NAME); if (!subjectAlternativeNames.isEmpty()) { boolean criticalNames = getProperty(PROPERTY_CERT_CRITICAL_NAMES, false); DERSequence subjectAlternativeNamesExtension = new DERSequence( subjectAlternativeNames.toArray(new ASN1Encodable[subjectAlternativeNames.size()])); extensions.add(new Extension(Extension.subjectAlternativeName, criticalNames, subjectAlternativeNamesExtension.getEncoded())); } if (issuerCertificate == null) { // crl distribution point DistributionPoint[] crlDistributionPoints = createCrlDistributionPoints(); if (crlDistributionPoints != null) { boolean criticalCrlDistPoints = getProperty(PROPERTY_CERT_CRITICAL_CRL_DISTRIBUTION_POINTS, false); extensions.add(new Extension(Extension.cRLDistributionPoints, criticalCrlDistPoints, new CRLDistPoint(crlDistributionPoints).getEncoded())); } // authority information access AccessDescription[] accessDescriptions = createAccessDescriptions(); if (accessDescriptions != null) { boolean criticalAuthorityInformationAccess = getProperty( PROPERTY_CERT_CRITICAL_AUTHORITY_INFORMATION_ACCESS, false); extensions.add(new Extension(Extension.authorityInfoAccess, criticalAuthorityInformationAccess, new AuthorityInformationAccess(accessDescriptions).getEncoded())); } } else { copyExtension(Extension.cRLDistributionPoints, issuerCertificate, extensions); copyExtension(Extension.authorityInfoAccess, issuerCertificate, extensions); } return extensions; }
From source file:org.xipki.commons.security.util.SignerUtil.java
License:Open Source License
public static byte[] convertPlainDSASigToX962(final byte[] signature) throws XiSecurityException { ParamUtil.requireNonNull("signature", signature); if (signature.length % 2 != 0) { throw new XiSecurityException("signature.lenth must be even, but is odd"); }//w w w .j ava 2s.c o m byte[] ba = new byte[signature.length / 2]; ASN1EncodableVector sigder = new ASN1EncodableVector(); System.arraycopy(signature, 0, ba, 0, ba.length); sigder.add(new ASN1Integer(new BigInteger(1, ba))); System.arraycopy(signature, ba.length, ba, 0, ba.length); sigder.add(new ASN1Integer(new BigInteger(1, ba))); DERSequence seq = new DERSequence(sigder); try { return seq.getEncoded(); } catch (IOException ex) { throw new XiSecurityException("IOException, message: " + ex.getMessage(), ex); } }
From source file:org.xipki.pki.ca.qa.ExtensionsChecker.java
License:Open Source License
public ExtensionsChecker(final X509ProfileType conf, final XmlX509Certprofile certProfile) throws CertprofileException { this.certProfile = ParamUtil.requireNonNull("certProfile", certProfile); ParamUtil.requireNonNull("conf", conf); // Extensions ExtensionsType extensionsType = conf.getExtensions(); // Extension controls Map<ASN1ObjectIdentifier, ExtensionControl> extensionControls = certProfile.getExtensionControls(); // Certificate Policies ASN1ObjectIdentifier type = Extension.certificatePolicies; if (extensionControls.containsKey(type)) { org.xipki.pki.ca.certprofile.x509.jaxb.CertificatePolicies extConf = (org.xipki.pki.ca.certprofile.x509.jaxb.CertificatePolicies) getExtensionValue( type, extensionsType, org.xipki.pki.ca.certprofile.x509.jaxb.CertificatePolicies.class); if (extConf != null) { this.certificatePolicies = new QaCertificatePolicies(extConf); }/*from w w w . j a v a 2 s . c om*/ } // Policy Mappings type = Extension.policyMappings; if (extensionControls.containsKey(type)) { PolicyMappings extConf = (PolicyMappings) getExtensionValue(type, extensionsType, PolicyMappings.class); if (extConf != null) { this.policyMappings = new QaPolicyMappingsOption(extConf); } } // Name Constrains type = Extension.nameConstraints; if (extensionControls.containsKey(type)) { org.xipki.pki.ca.certprofile.x509.jaxb.NameConstraints extConf = (org.xipki.pki.ca.certprofile.x509.jaxb.NameConstraints) getExtensionValue( type, extensionsType, org.xipki.pki.ca.certprofile.x509.jaxb.NameConstraints.class); if (extConf != null) { this.nameConstraints = new QaNameConstraints(extConf); } } // Policy Constraints type = Extension.policyConstraints; if (extensionControls.containsKey(type)) { PolicyConstraints extConf = (PolicyConstraints) getExtensionValue(type, extensionsType, PolicyConstraints.class); if (extConf != null) { this.policyConstraints = new QaPolicyConstraints(extConf); } } // Inhibit anyPolicy type = Extension.inhibitAnyPolicy; if (extensionControls.containsKey(type)) { InhibitAnyPolicy extConf = (InhibitAnyPolicy) getExtensionValue(type, extensionsType, InhibitAnyPolicy.class); if (extConf != null) { this.inhibitAnyPolicy = new QaInhibitAnyPolicy(extConf); } } // restriction type = ObjectIdentifiers.id_extension_restriction; if (extensionControls.containsKey(type)) { Restriction extConf = (Restriction) getExtensionValue(type, extensionsType, Restriction.class); if (extConf != null) { restriction = new QaDirectoryString( XmlX509CertprofileUtil.convertDirectoryStringType(extConf.getType()), extConf.getText()); } } // additionalInformation type = ObjectIdentifiers.id_extension_additionalInformation; if (extensionControls.containsKey(type)) { AdditionalInformation extConf = (AdditionalInformation) getExtensionValue(type, extensionsType, AdditionalInformation.class); if (extConf != null) { additionalInformation = new QaDirectoryString( XmlX509CertprofileUtil.convertDirectoryStringType(extConf.getType()), extConf.getText()); } } // validityModel type = ObjectIdentifiers.id_extension_validityModel; if (extensionControls.containsKey(type)) { ValidityModel extConf = (ValidityModel) getExtensionValue(type, extensionsType, ValidityModel.class); if (extConf != null) { validityModelId = new ASN1ObjectIdentifier(extConf.getModelId().getValue()); } } // QCStatements type = Extension.qCStatements; if (extensionControls.containsKey(type)) { QcStatements extConf = (QcStatements) getExtensionValue(type, extensionsType, QcStatements.class); if (extConf != null) { qcStatements = extConf; } } // tlsFeature type = ObjectIdentifiers.id_pe_tlsfeature; if (extensionControls.containsKey(type)) { TlsFeature extConf = (TlsFeature) getExtensionValue(type, extensionsType, TlsFeature.class); if (extConf != null) { tlsFeature = new QaTlsFeature(extConf); } } // AuthorizationTemplate type = ObjectIdentifiers.id_xipki_ext_authorizationTemplate; if (extensionControls.containsKey(type)) { AuthorizationTemplate extConf = (AuthorizationTemplate) getExtensionValue(type, extensionsType, AuthorizationTemplate.class); if (extConf != null) { authorizationTemplate = new QaAuthorizationTemplate(extConf); } } // SMIMECapabilities type = ObjectIdentifiers.id_smimeCapabilities; if (extensionControls.containsKey(type)) { SMIMECapabilities extConf = (SMIMECapabilities) getExtensionValue(type, extensionsType, SMIMECapabilities.class); List<SMIMECapability> list = extConf.getSMIMECapability(); ASN1EncodableVector vec = new ASN1EncodableVector(); for (SMIMECapability m : list) { ASN1ObjectIdentifier oid = new ASN1ObjectIdentifier(m.getCapabilityID().getValue()); ASN1Encodable params = null; org.xipki.pki.ca.certprofile.x509.jaxb.SMIMECapability.Parameters capParams = m.getParameters(); if (capParams != null) { if (capParams.getInteger() != null) { params = new ASN1Integer(capParams.getInteger()); } else if (capParams.getBase64Binary() != null) { params = readAsn1Encodable(capParams.getBase64Binary().getValue()); } } org.bouncycastle.asn1.smime.SMIMECapability cap = new org.bouncycastle.asn1.smime.SMIMECapability( oid, params); vec.add(cap); } DERSequence extValue = new DERSequence(vec); try { smimeCapabilities = new QaExtensionValue(extensionControls.get(type).isCritical(), extValue.getEncoded()); } catch (IOException ex) { throw new CertprofileException("Cannot encode SMIMECapabilities: " + ex.getMessage()); } } // constant extensions this.constantExtensions = buildConstantExtesions(extensionsType); }
From source file:org.xipki.security.p11.iaik.IaikP11Slot.java
License:Open Source License
private X509CertificateHolder generateCertificate(final Session session, final byte[] id, final String label, final String subject, final AlgorithmIdentifier signatureAlgId, final PrivateKeyAndPKInfo privateKeyAndPkInfo, Integer keyUsage, List<ASN1ObjectIdentifier> extendedKeyUsage) throws Exception { BigInteger serialNumber = BigInteger.ONE; Date startDate = new Date(); Date endDate = new Date(startDate.getTime() + 20 * YEAR); X500Name x500Name_subject = new X500Name(subject); x500Name_subject = X509Util.sortX509Name(x500Name_subject); V3TBSCertificateGenerator tbsGen = new V3TBSCertificateGenerator(); tbsGen.setSerialNumber(new ASN1Integer(serialNumber)); tbsGen.setSignature(signatureAlgId); tbsGen.setIssuer(x500Name_subject); tbsGen.setStartDate(new Time(startDate)); tbsGen.setEndDate(new Time(endDate)); tbsGen.setSubject(x500Name_subject); tbsGen.setSubjectPublicKeyInfo(privateKeyAndPkInfo.getPublicKeyInfo()); List<Extension> extensions = new ArrayList<>(2); if (keyUsage == null) { keyUsage = KeyUsage.keyCertSign | KeyUsage.cRLSign | KeyUsage.digitalSignature | KeyUsage.keyEncipherment; }/*from w ww . j a v a 2s.c o m*/ extensions.add(new Extension(Extension.keyUsage, true, new DEROctetString(new KeyUsage(keyUsage)))); if (CollectionUtil.isNotEmpty(extendedKeyUsage)) { KeyPurposeId[] kps = new KeyPurposeId[extendedKeyUsage.size()]; int i = 0; for (ASN1ObjectIdentifier oid : extendedKeyUsage) { kps[i++] = KeyPurposeId.getInstance(oid); } extensions.add(new Extension(Extension.extendedKeyUsage, false, new DEROctetString(new ExtendedKeyUsage(kps)))); } Extensions paramX509Extensions = new Extensions(extensions.toArray(new Extension[0])); tbsGen.setExtensions(paramX509Extensions); TBSCertificate tbsCertificate = tbsGen.generateTBSCertificate(); byte[] encodedTbsCertificate = tbsCertificate.getEncoded(); byte[] signature = null; Digest digest = null; Mechanism sigMechanism = null; ASN1ObjectIdentifier sigAlgID = signatureAlgId.getAlgorithm(); if (sigAlgID.equals(PKCSObjectIdentifiers.sha256WithRSAEncryption)) { sigMechanism = Mechanism.get(PKCS11Constants.CKM_SHA256_RSA_PKCS); session.signInit(sigMechanism, privateKeyAndPkInfo.getPrivateKey()); signature = session.sign(encodedTbsCertificate); } else if (sigAlgID.equals(NISTObjectIdentifiers.dsa_with_sha256)) { digest = new SHA256Digest(); byte[] digestValue = new byte[digest.getDigestSize()]; digest.update(encodedTbsCertificate, 0, encodedTbsCertificate.length); digest.doFinal(digestValue, 0); session.signInit(Mechanism.get(PKCS11Constants.CKM_DSA), privateKeyAndPkInfo.getPrivateKey()); byte[] rawSignature = session.sign(digestValue); signature = convertToX962Signature(rawSignature); } else { if (sigAlgID.equals(X9ObjectIdentifiers.ecdsa_with_SHA1)) { digest = new SHA1Digest(); } else if (sigAlgID.equals(X9ObjectIdentifiers.ecdsa_with_SHA256)) { digest = new SHA256Digest(); } else if (sigAlgID.equals(X9ObjectIdentifiers.ecdsa_with_SHA384)) { digest = new SHA384Digest(); } else if (sigAlgID.equals(X9ObjectIdentifiers.ecdsa_with_SHA512)) { digest = new SHA512Digest(); } else { System.err.println("unknown algorithm ID: " + sigAlgID.getId()); return null; } byte[] digestValue = new byte[digest.getDigestSize()]; digest.update(encodedTbsCertificate, 0, encodedTbsCertificate.length); digest.doFinal(digestValue, 0); session.signInit(Mechanism.get(PKCS11Constants.CKM_ECDSA), privateKeyAndPkInfo.getPrivateKey()); byte[] rawSignature = session.sign(digestValue); signature = convertToX962Signature(rawSignature); } // build DER certificate ASN1EncodableVector v = new ASN1EncodableVector(); v.add(tbsCertificate); v.add(signatureAlgId); v.add(new DERBitString(signature)); DERSequence cert = new DERSequence(v); // build and store PKCS#11 certificate object X509PublicKeyCertificate certTemp = new X509PublicKeyCertificate(); certTemp.getToken().setBooleanValue(true); certTemp.getId().setByteArrayValue(id); certTemp.getLabel().setCharArrayValue(label.toCharArray()); certTemp.getSubject().setByteArrayValue(x500Name_subject.getEncoded()); certTemp.getIssuer().setByteArrayValue(x500Name_subject.getEncoded()); certTemp.getSerialNumber().setByteArrayValue(serialNumber.toByteArray()); certTemp.getValue().setByteArrayValue(cert.getEncoded()); session.createObject(certTemp); return new X509CertificateHolder(Certificate.getInstance(cert)); }
From source file:org.xipki.security.SignerUtil.java
License:Open Source License
public static byte[] convertPlainDSASigX962(final byte[] signature) throws SignerException { byte[] ba = new byte[signature.length / 2]; ASN1EncodableVector sigder = new ASN1EncodableVector(); System.arraycopy(signature, 0, ba, 0, ba.length); sigder.add(new ASN1Integer(new BigInteger(1, ba))); System.arraycopy(signature, ba.length, ba, 0, ba.length); sigder.add(new ASN1Integer(new BigInteger(1, ba))); DERSequence seq = new DERSequence(sigder); try {/*from ww w . j a va2s. c o m*/ return seq.getEncoded(); } catch (IOException e) { throw new SignerException("IOException, message: " + e.getMessage(), e); } }
From source file:test.unit.be.fedict.eid.applet.DerTest.java
License:Open Source License
@Test public void derSequence() throws Exception { DERSequence derSequence = new DERSequence(); byte[] encodedDerSequence = derSequence.getEncoded(); LOG.debug("DER sequence size: " + encodedDerSequence.length); LOG.debug("DER sequence: " + new String(Hex.encodeHex(encodedDerSequence))); LOG.debug("ASN.1 DER sequence: " + ASN1Dump.dumpAsString(derSequence)); DERInteger derInteger = new DERInteger(1234); byte[] encodedDerInteger = derInteger.getDEREncoded(); LOG.debug("DER integer: " + new String(Hex.encodeHex(encodedDerInteger))); }