List of usage examples for org.bouncycastle.asn1.pkcs Attribute getAttrType
public ASN1ObjectIdentifier getAttrType()
From source file:com.vvote.thirdparty.ximix.util.BLSKeyStore.java
License:Apache License
private String getKeyID(Attribute[] attributes) { for (Attribute attr : attributes) { if (PKCS12SafeBag.friendlyNameAttribute.equals(attr.getAttrType())) { return DERBMPString.getInstance(attr.getAttrValues().getObjectAt(0)).getString(); }//from w w w. ja v a 2 s.c o m } throw new IllegalStateException("No friendlyNameAttribute found."); }
From source file:de.carne.certmgr.store.provider.bouncycastle.BouncyCastlePKCS10Object.java
License:Open Source License
@Override public Set<String> getAttributeOIDs() { HashSet<String> oids = new HashSet<>(); for (Attribute attribute : this.pkcs10Object.getAttributes()) { oids.add(attribute.getAttrType().getId()); }//from www . j a va2 s .c om return oids; }
From source file:de.carne.certmgr.store.provider.bouncycastle.PKCS12Decoder.java
License:Open Source License
public void decodeCRTBag(X509CertificateHolder bagValue, Attribute[] bagAttributes) { try {/*from w w w . ja v a2 s. co m*/ X509Certificate crt = this.jcaConverter.getCertificate(bagValue); this.decoded.add(crt); for (Attribute bagAttribute : bagAttributes) { if (bagAttribute.getAttrType().equals(PKCS12SafeBag.localKeyIdAttribute)) { decodeKey(bagAttribute.getAttributeValues()[0], crt.getPublicKey()); break; } } } catch (Exception e) { LOG.info(e, null, "Unable to decode CRT data from PKCS#12 bag"); } }
From source file:de.carne.certmgr.store.provider.bouncycastle.PKCS12Decoder.java
License:Open Source License
public void decodeKeyBag(PrivateKeyInfo bagValue, Attribute[] bagAttributes) { try {//from w w w.j ava 2s. com KeyFactory keyFactory = KeyFactory.getInstance(bagValue.getPrivateKeyAlgorithm().getAlgorithm().getId(), BouncyCastleProvider.PROVIDER_NAME); PrivateKey privateKey = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(bagValue.getEncoded())); for (Attribute bagAttribute : bagAttributes) { if (bagAttribute.getAttrType().equals(PKCS12SafeBag.localKeyIdAttribute)) { decodeKey(bagAttribute.getAttributeValues()[0], privateKey); break; } } } catch (Exception e) { LOG.info(e, null, "Unable to decode key data from PKCS#12 bag"); } }
From source file:eu.betaas.taas.securitymanager.common.certificate.utils.PKCS12Utils.java
License:Apache License
/** * A method to load BcCredential (consists of certificate chain, end entity * alias and private key of end entity credential) from the PKCS12 file * @param pkcs12FileName: the PKCS12 file name * @param keyPasswd: the password of the key credential * @return/*from ww w . j a va 2 s .c o m*/ * @throws Exception */ public static BcCredential loadPKCS12Credential(String pkcs12FileName, char[] keyPasswd, int certType) { PKCS12PfxPdu pfxPdu = null; // if(certType == APPS_CERT){ // log.info("Reading AppStoreCertInter.p12 file"); // InputStream is = PKCS12Utils.class.getResourceAsStream(pkcs12FileName); // log.info("AppStoreCertInter.p12 file has been converted to InputStream"); // pfxPdu = new PKCS12PfxPdu(Streams.readAll(is)); // log.info("Read the PKCS12PfxPdu..."); // } // else if(certType == GW_CERT){ // Try to put the AppStoreCertInter.p12 in the karaf, so no need to read // from the resource, e.g. getResourceAsStream log.debug("will start loading PKCS12 file..."); try { pfxPdu = new PKCS12PfxPdu(Streams.readAll(new FileInputStream(pkcs12FileName))); } catch (FileNotFoundException e) { // TODO Auto-generated catch block log.error("PKCS12 file: " + pkcs12FileName + " is not found!!"); e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block log.error("IOException in initializing PKCS12PfxPdu..."); e.printStackTrace(); } log.debug("Loading PKCS12 successfully..."); // } try { if (!pfxPdu.isMacValid(new BcPKCS12MacCalculatorBuilderProvider(BcDefaultDigestProvider.INSTANCE), keyPasswd)) { log.error("PKCS#12 MAC test failed!"); return null; } } catch (PKCSException e) { // TODO Auto-generated catch block e.printStackTrace(); } ContentInfo[] infos = pfxPdu.getContentInfos(); InputDecryptorProvider inputDecryptorProvider = new BcPKCS12PBEInputDecryptorProviderBuilder() .build(keyPasswd); String eeAlias = null; AsymmetricKeyParameter privCred = null; List<X509CertificateHolder> chainList = new ArrayList<X509CertificateHolder>(); // log.info("Start iterating over the ContentInfo..."); for (int i = 0; i != infos.length; i++) { if (infos[i].getContentType().equals(PKCSObjectIdentifiers.encryptedData)) { PKCS12SafeBagFactory dataFact = null; try { dataFact = new PKCS12SafeBagFactory(infos[i], inputDecryptorProvider); } catch (PKCSException e) { // TODO Auto-generated catch block log.error("Error in initiating PKCS12SafeBagFactory..."); e.printStackTrace(); } PKCS12SafeBag[] bags = dataFact.getSafeBags(); for (int b = 0; b != bags.length; b++) { PKCS12SafeBag bag = bags[b]; X509CertificateHolder certHldr = (X509CertificateHolder) bag.getBagValue(); chainList.add(certHldr); log.debug("Found a certificate and add it to certificate chain..."); } } else { PKCS12SafeBagFactory dataFact = new PKCS12SafeBagFactory(infos[i]); PKCS12SafeBag[] bags = dataFact.getSafeBags(); PKCS8EncryptedPrivateKeyInfo encInfo = (PKCS8EncryptedPrivateKeyInfo) bags[0].getBagValue(); PrivateKeyInfo info; AsymmetricKeyParameter privKey = null; try { info = encInfo.decryptPrivateKeyInfo(inputDecryptorProvider); privKey = PrivateKeyFactory.createKey(info); } catch (PKCSException e) { // TODO Auto-generated catch block log.error("Error in getting the decrypt private key info..."); e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block log.error("Error in loading private key..."); e.printStackTrace(); } Attribute[] attributes = bags[0].getAttributes(); for (int a = 0; a != attributes.length; a++) { Attribute attr = attributes[a]; if (attr.getAttrType().equals(PKCS12SafeBag.friendlyNameAttribute)) { eeAlias = ((DERBMPString) attr.getAttributeValues()[0]).getString(); privCred = privKey; log.debug("Get end entity alias"); log.debug("Priv. credential D: " + ((ECPrivateKeyParameters) privCred).getD().toString()); } } } } X509CertificateHolder[] chain = new X509CertificateHolder[chainList.size()]; chain = (X509CertificateHolder[]) chainList.toArray(chain); BcCredential cred = new BcCredential(eeAlias, privCred, chain); log.debug("Credential has been loaded!!"); return cred; }
From source file:eu.betaas.taas.securitymanager.common.certificate.utils.PKCS12Utils.java
License:Apache License
/** * A method to load BcCredential (consists of certificate chain, end entity * alias and private key of end entity credential) from the PKCS12 file * @param pfx: the PKCS#12 file in byte/*from ww w . j a v a 2s . co m*/ * @param keyPasswd: the password of the key credential * @return * @throws Exception */ public static BcCredential loadPKCS12Credential(byte[] pfx, char[] keyPasswd) throws Exception { PKCS12PfxPdu pfxPdu = new PKCS12PfxPdu(pfx); if (!pfxPdu.isMacValid(new BcPKCS12MacCalculatorBuilderProvider(BcDefaultDigestProvider.INSTANCE), keyPasswd)) { log.error("PKCS#12 MAC test failed!"); return null; } ContentInfo[] infos = pfxPdu.getContentInfos(); InputDecryptorProvider inputDecryptorProvider = new BcPKCS12PBEInputDecryptorProviderBuilder() .build(keyPasswd); String eeAlias = null; AsymmetricKeyParameter privCred = null; List<X509CertificateHolder> chainList = new ArrayList<X509CertificateHolder>(); // log.debug("Start iterating over the ContentInfo..."); for (int i = 0; i != infos.length; i++) { if (infos[i].getContentType().equals(PKCSObjectIdentifiers.encryptedData)) { PKCS12SafeBagFactory dataFact = new PKCS12SafeBagFactory(infos[i], inputDecryptorProvider); PKCS12SafeBag[] bags = dataFact.getSafeBags(); for (int b = 0; b != bags.length; b++) { PKCS12SafeBag bag = bags[b]; X509CertificateHolder certHldr = (X509CertificateHolder) bag.getBagValue(); chainList.add(certHldr); log.debug("Found a certificate and add it to certificate chain..."); } } else { PKCS12SafeBagFactory dataFact = new PKCS12SafeBagFactory(infos[i]); PKCS12SafeBag[] bags = dataFact.getSafeBags(); PKCS8EncryptedPrivateKeyInfo encInfo = (PKCS8EncryptedPrivateKeyInfo) bags[0].getBagValue(); PrivateKeyInfo info = encInfo.decryptPrivateKeyInfo(inputDecryptorProvider); AsymmetricKeyParameter privKey = PrivateKeyFactory.createKey(info); Attribute[] attributes = bags[0].getAttributes(); for (int a = 0; a != attributes.length; a++) { Attribute attr = attributes[a]; if (attr.getAttrType().equals(PKCS12SafeBag.friendlyNameAttribute)) { eeAlias = ((DERBMPString) attr.getAttributeValues()[0]).getString(); privCred = privKey; log.debug("Get end entity alias"); log.debug("Priv. credential D: " + ((ECPrivateKeyParameters) privCred).getD().toString()); } } } } X509CertificateHolder[] chain = new X509CertificateHolder[chainList.size()]; chain = (X509CertificateHolder[]) chainList.toArray(chain); BcCredential cred = new BcCredential(eeAlias, privCred, chain); return cred; }
From source file:eu.europa.esig.dss.pades.InfiniteLoopDSS621Test.java
License:Open Source License
/** * These signatures are invalid because of non ordered signed attributes *//*from w ww .j a va2s. c o m*/ @Test public void manualTest() throws Exception { File pdfFile = new File(FILE_PATH); FileInputStream fis = new FileInputStream(pdfFile); byte[] pdfBytes = IOUtils.toByteArray(fis); PDDocument document = PDDocument.load(pdfFile); List<PDSignature> signatures = document.getSignatureDictionaries(); assertEquals(6, signatures.size()); int idx = 0; for (PDSignature pdSignature : signatures) { byte[] contents = pdSignature.getContents(pdfBytes); byte[] signedContent = pdSignature.getSignedContent(pdfBytes); logger.info("Byte range : " + Arrays.toString(pdSignature.getByteRange())); IOUtils.write(contents, new FileOutputStream("target/sig" + (idx++) + ".p7s")); ASN1InputStream asn1sInput = new ASN1InputStream(contents); ASN1Sequence asn1Seq = (ASN1Sequence) asn1sInput.readObject(); logger.info("SEQ : " + asn1Seq.toString()); ASN1ObjectIdentifier oid = ASN1ObjectIdentifier.getInstance(asn1Seq.getObjectAt(0)); assertEquals(PKCSObjectIdentifiers.signedData, oid); SignedData signedData = SignedData .getInstance(DERTaggedObject.getInstance(asn1Seq.getObjectAt(1)).getObject()); ASN1Set digestAlgorithmSet = signedData.getDigestAlgorithms(); ASN1ObjectIdentifier oidDigestAlgo = ASN1ObjectIdentifier .getInstance(ASN1Sequence.getInstance(digestAlgorithmSet.getObjectAt(0)).getObjectAt(0)); DigestAlgorithm digestAlgorithm = DigestAlgorithm.forOID(oidDigestAlgo.getId()); logger.info("DIGEST ALGO : " + digestAlgorithm); ContentInfo encapContentInfo = signedData.getEncapContentInfo(); ASN1ObjectIdentifier contentTypeOID = encapContentInfo.getContentType(); logger.info("ENCAPSULATED CONTENT INFO TYPE : " + contentTypeOID); if (!PKCSObjectIdentifiers.id_ct_TSTInfo.equals(contentTypeOID)) { // If not timestamp assertEquals(PKCSObjectIdentifiers.data, contentTypeOID); ASN1Encodable content = encapContentInfo.getContent(); logger.info("ENCAPSULATED CONTENT INFO CONTENT : " + content); assertNull(content); List<X509Certificate> certificates = extractCertificates(signedData); ASN1Set signerInfosAsn1 = signedData.getSignerInfos(); logger.info("SIGNER INFO ASN1 : " + signerInfosAsn1.toString()); SignerInfo signedInfo = SignerInfo .getInstance(ASN1Sequence.getInstance(signerInfosAsn1.getObjectAt(0))); ASN1Set authenticatedAttributeSet = signedInfo.getAuthenticatedAttributes(); logger.info("AUTHENTICATED ATTR : " + authenticatedAttributeSet); Attribute attributeDigest = null; for (int i = 0; i < authenticatedAttributeSet.size(); i++) { Attribute attribute = Attribute.getInstance(authenticatedAttributeSet.getObjectAt(i)); if (PKCSObjectIdentifiers.pkcs_9_at_messageDigest.equals(attribute.getAttrType())) { attributeDigest = attribute; break; } } assertNotNull(attributeDigest); ASN1OctetString asn1ObjString = ASN1OctetString .getInstance(attributeDigest.getAttrValues().getObjectAt(0)); String embeddedDigest = Base64.encodeBase64String(asn1ObjString.getOctets()); logger.info("MESSAGE DIGEST : " + embeddedDigest); byte[] digestSignedContent = DSSUtils.digest(digestAlgorithm, signedContent); String computedDigestSignedContentEncodeBase64 = Base64.encodeBase64String(digestSignedContent); logger.info("COMPUTED DIGEST SIGNED CONTENT BASE64 : " + computedDigestSignedContentEncodeBase64); assertEquals(embeddedDigest, computedDigestSignedContentEncodeBase64); SignerIdentifier sid = signedInfo.getSID(); logger.info("SIGNER IDENTIFIER : " + sid.getId()); IssuerAndSerialNumber issuerAndSerialNumber = IssuerAndSerialNumber .getInstance(signedInfo.getSID()); ASN1Integer signerSerialNumber = issuerAndSerialNumber.getSerialNumber(); logger.info("ISSUER AND SN : " + issuerAndSerialNumber.getName() + " " + signerSerialNumber); BigInteger serial = issuerAndSerialNumber.getSerialNumber().getValue(); X509Certificate signerCertificate = null; for (X509Certificate x509Certificate : certificates) { if (serial.equals(x509Certificate.getSerialNumber())) { signerCertificate = x509Certificate; } } assertNotNull(signerCertificate); String algorithm = signerCertificate.getPublicKey().getAlgorithm(); EncryptionAlgorithm encryptionAlgorithm = EncryptionAlgorithm.forName(algorithm); ASN1OctetString encryptedInfoOctedString = signedInfo.getEncryptedDigest(); String signatureValue = Hex.toHexString(encryptedInfoOctedString.getOctets()); logger.info("SIGNATURE VALUE : " + signatureValue); Cipher cipher = Cipher.getInstance(encryptionAlgorithm.getName()); cipher.init(Cipher.DECRYPT_MODE, signerCertificate); byte[] decrypted = cipher.doFinal(encryptedInfoOctedString.getOctets()); ASN1InputStream inputDecrypted = new ASN1InputStream(decrypted); ASN1Sequence seqDecrypt = (ASN1Sequence) inputDecrypted.readObject(); logger.info("DECRYPTED : " + seqDecrypt); DigestInfo digestInfo = new DigestInfo(seqDecrypt); assertEquals(oidDigestAlgo, digestInfo.getAlgorithmId().getAlgorithm()); String decryptedDigestEncodeBase64 = Base64.encodeBase64String(digestInfo.getDigest()); logger.info("DECRYPTED BASE64 : " + decryptedDigestEncodeBase64); byte[] encoded = authenticatedAttributeSet.getEncoded(); byte[] digest = DSSUtils.digest(digestAlgorithm, encoded); String computedDigestFromSignatureEncodeBase64 = Base64.encodeBase64String(digest); logger.info("COMPUTED DIGEST FROM SIGNATURE BASE64 : " + computedDigestFromSignatureEncodeBase64); assertEquals(decryptedDigestEncodeBase64, computedDigestFromSignatureEncodeBase64); IOUtils.closeQuietly(inputDecrypted); } IOUtils.closeQuietly(asn1sInput); } IOUtils.closeQuietly(fis); document.close(); }
From source file:io.aos.crypto.spl06.PKCS10CertCreateExample.java
License:Apache License
public static X509Certificate[] buildChain() throws Exception { // create the certification request KeyPair pair = Utils.generateRSAKeyPair(); PKCS10CertificationRequest request = PKCS10ExtensionExample.generateRequest(pair); // create a root certificate KeyPair rootPair = Utils.generateRSAKeyPair(); X509Certificate rootCert = X509V1CreateExample.generateV1Certificate(rootPair); // validate the certification request if (!request.verify("BC")) { System.out.println("request failed to verify!"); System.exit(1);/* w ww.j av a 2 s.c om*/ } // create the certificate using the information in the request X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setIssuerDN(rootCert.getSubjectX500Principal()); certGen.setNotBefore(new Date(System.currentTimeMillis())); certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000)); certGen.setSubjectDN(request.getCertificationRequestInfo().getSubject()); certGen.setPublicKey(request.getPublicKey("BC")); certGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(rootCert)); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(request.getPublicKey("BC"))); certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); certGen.addExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth)); // extract the extension request attribute ASN1Set attributes = request.getCertificationRequestInfo().getAttributes(); for (int i = 0; i != attributes.size(); i++) { Attribute attr = Attribute.getInstance(attributes.getObjectAt(i)); // process extension request if (attr.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) { X509Extensions extensions = X509Extensions.getInstance(attr.getAttrValues().getObjectAt(0)); Enumeration e = extensions.oids(); while (e.hasMoreElements()) { DERObjectIdentifier oid = (DERObjectIdentifier) e.nextElement(); X509Extension ext = extensions.getExtension(oid); certGen.addExtension(oid, ext.isCritical(), ext.getValue().getOctets()); } } } X509Certificate issuedCert = certGen.generateX509Certificate(rootPair.getPrivate()); return new X509Certificate[] { issuedCert, rootCert }; }
From source file:net.felsing.client_cert.utilities.CertificateFabric.java
License:Open Source License
private void getSubjectAlternativeNames(PKCS10CertificationRequest csr) { subjectAlternativeNames = new ArrayList<>(new ArrayList<>()); // GeneralName.otherName is lowest and // GeneralName.registeredID is highest id for (int i = GeneralName.otherName; i <= GeneralName.registeredID; i++) { subjectAlternativeNames.add(new ArrayList<>()); }// www. ja v a 2s .c o m try { Attribute[] certAttributes = csr.getAttributes(); for (Attribute attribute : certAttributes) { if (attribute.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) { // @ToDo: Is there really one object only? Extensions extensions = Extensions.getInstance(attribute.getAttrValues().getObjectAt(0)); GeneralNames gns = GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName); if (gns != null) { GeneralName[] names = gns.getNames(); for (GeneralName name : names) { subjectAlternativeNames.get(name.getTagNo()).add(name.getName().toString()); } } } } } catch (Exception e) { e.printStackTrace(); } }
From source file:net.ripe.rpki.commons.provisioning.x509.pkcs10.RpkiCaCertificateRequestParser.java
License:BSD License
private ASN1Set getPkcs9ExtensionRequest() throws RpkiCaCertificateRequestParserException { Attribute[] attributes = pkcs10CertificationRequest.getAttributes(); for (Attribute attr : attributes) { ASN1ObjectIdentifier oid = attr.getAttrType(); if (oid.equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) { return attr.getAttrValues(); }/*from w w w . j a va 2 s . co m*/ } throw new RpkiCaCertificateRequestParserException("Could not find PKCS 9 Extension Request"); }