List of usage examples for org.bouncycastle.cert X509CertificateHolder getSubjectPublicKeyInfo
public SubjectPublicKeyInfo getSubjectPublicKeyInfo()
From source file:beta01.ReadPkc12.java
public static void main(String[] args) throws KeyStoreException, NoSuchProviderException, IOException, NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException { KeyStore pkcs12Store = KeyStore.getInstance("PKCS12", "BC"); pkcs12Store.load(new FileInputStream("D:\\rootPrivateKeySS.p12"), "pass".toCharArray()); System.out.println("########## KeyStore Dump. Size: " + pkcs12Store.size()); //KeyPair/*from w w w .ja v a 2 s . c om*/ PrivateKey privateKey = null; for (Enumeration en = pkcs12Store.aliases(); en.hasMoreElements();) { String alias = (String) en.nextElement(); if (pkcs12Store.isCertificateEntry(alias)) { X509Certificate cc = (X509Certificate) pkcs12Store.getCertificate(alias); X509CertificateHolder holder = new JcaX509CertificateHolder(cc); SubjectPublicKeyInfo pkInfo = holder.getSubjectPublicKeyInfo(); Certificate cert = pkcs12Store.getCertificate(alias); //System.out.println("Signature: "+cert.getType()+" "+cert.getPublicKey()); PublicKey publicKey = cert.getPublicKey(); System.out.println("Certificate Entry: " + alias + ", Subject: " + (((X509Certificate) pkcs12Store.getCertificate(alias)).getSubjectDN())); //test signing Signature dsa = Signature.getInstance("SHA512withRSA"); String data = "DATA55555556666666..."; try { dsa.initSign(privateKey); dsa.update(data.getBytes()); byte[] realSign = dsa.sign(); //X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(publicKey.getEncoded()); //KeyFactory keyFactory = KeyFactory.getInstance("RSA"); //pk2 = keyFactory.generatePublic(pubKeySpec); dsa.initVerify(publicKey); dsa.update(data.getBytes()); System.out.println("Is verivied? " + dsa.verify(realSign)); } catch (InvalidKeyException | SignatureException ex) { Logger.getLogger(ReadPkc12.class.getName()).log(Level.SEVERE, null, ex); } } else if (pkcs12Store.isKeyEntry(alias)) { privateKey = (PrivateKey) pkcs12Store.getKey(alias, "pass".toCharArray()); System.out.println("Key Entry: [" + privateKey.getAlgorithm() + "]" + alias + ", Subject: " + (((X509Certificate) pkcs12Store.getCertificate(alias)).getSubjectDN())); } } }
From source file:com.nimbusds.jose.jwk.PEMEncodedKeyParser.java
License:Apache License
private static KeyPair toKeyPair(final X509CertificateHolder pemObj) throws PEMException { final SubjectPublicKeyInfo spki = pemObj.getSubjectPublicKeyInfo(); return new KeyPair(pemConverter.getPublicKey(spki), null); }
From source file:com.vvote.thirdparty.ximix.util.BLSKeyStore.java
License:Apache License
/** * Load the key store object from the passed in PKCS#12 encoding, using the passed in password. * * @param password the password to unlock the key store. * @param encoding the ASN.1 encoded bytes representing the PKCS#12 store. * @throws IOException on a parsing error. * @throws GeneralSecurityException if there's an exception decrypting the store. *//*from w ww .ja v a 2s .c o m*/ public synchronized void load(char[] password, byte[] encoding) throws IOException, GeneralSecurityException { try { PKCS12PfxPdu pfx = new PKCS12PfxPdu(encoding); InputDecryptorProvider inputDecryptorProvider = new JcePKCSPBEInputDecryptorProviderBuilder() .setProvider("BC").build(password); ContentInfo[] infos = pfx.getContentInfos(); 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(); Attribute[] attributes = bags[0].getAttributes(); X509CertificateHolder cert = (X509CertificateHolder) bags[0].getBagValue(); String keyID = getKeyID(attributes); BLS01PublicKeyParameters publicKeyParameters = BLSPublicKeyFactory .createKey(cert.getSubjectPublicKeyInfo()); paramsMap.put(keyID, publicKeyParameters.getParameters()); sequenceNoMap.put(keyID, ASN1Integer.getInstance( cert.getExtension(XimixObjectIdentifiers.ximixShareIdExtension).getParsedValue()) .getValue().intValue()); sharedPublicKeyMap.put(keyID, publicKeyParameters.getPk()); if (KeyUsage.fromExtensions(cert.getExtensions()).hasUsages(KeyUsage.digitalSignature)) { signingKeys.add(keyID); } } else { PKCS12SafeBagFactory dataFact = new PKCS12SafeBagFactory(infos[i]); PKCS12SafeBag[] bags = dataFact.getSafeBags(); String keyID = getKeyID(bags[0].getAttributes()); PKCS8EncryptedPrivateKeyInfo encInfo = (PKCS8EncryptedPrivateKeyInfo) bags[0].getBagValue(); PrivateKeyInfo info = encInfo.decryptPrivateKeyInfo(inputDecryptorProvider); sharedPrivateKeyMap.put(keyID, ASN1Integer.getInstance(info.parsePrivateKey()).getValue()); } } } catch (PKCSException e) { throw new GeneralSecurityException("Unable to load key store: " + e.getMessage(), e); } }
From source file:ee.ria.xroad.common.ocsp.OcspVerifier.java
License:Open Source License
/** * @param response the OCSP response/* ww w.j ava2 s .com*/ * @return certificate that was used to sign the given OCSP response. * @throws Exception if an error occurs */ public static X509Certificate getOcspCert(BasicOCSPResp response) throws Exception { List<X509Certificate> knownCerts = getOcspCerts(response); ResponderID respId = response.getResponderId().toASN1Primitive(); // We can search either by key hash or by name, depending which // one is provided in the responder ID. if (respId.getName() != null) { for (X509Certificate cert : knownCerts) { X509CertificateHolder certHolder = new X509CertificateHolder(cert.getEncoded()); if (certHolder.getSubject().equals(respId.getName())) { return cert; } } } else if (respId.getKeyHash() != null) { DigestCalculator dc = createDigestCalculator(SHA1_ID); for (X509Certificate cert : knownCerts) { X509CertificateHolder certHolder = new X509CertificateHolder(cert.getEncoded()); DERBitString keyData = certHolder.getSubjectPublicKeyInfo().getPublicKeyData(); byte[] d = calculateDigest(dc, keyData.getBytes()); if (MessageDigestAlgorithm.isEqual(respId.getKeyHash(), d)) { return cert; } } } return null; }
From source file:eu.betaas.service.securitymanager.service.impl.AuthorizationService.java
License:Apache License
/** * Method to form an ExternalCapability especially in Apps. installation * @param thingServiceId/* w w w . jav a2 s . c om*/ * @param subjectType * @param appId * @param myCertByte * @return * @throws JAXBException * @throws OperatorCreationException * @throws CMSException * @throws IOException */ private CapabilityExternal getTokenAppsLocal(String thingServiceId, String subjectType, String appId, byte[] myCertByte) throws Exception { log.debug("Start creating capability external..."); CapabilityExternal exCap = new CapabilityExternal(); exCap.setResourceId(thingServiceId); exCap.setRevocationUrl(REVOCATION_URL); // Issuer Info IssuerInfo ii = new IssuerInfo(); ii.setIssuerCertificate(myCertByte); ii.setIssuerType(IssuerType.GATEWAY_TYPE); exCap.setIssuerInfo(ii); // create SubjectInfo class and then add it to the exCap SubjectInfo si = new SubjectInfo(); si.setSubjectType(subjectType); // get SubjectPublicKeyInfo from apps certificate --> from appId X509CertificateHolder appsCert = appCertCatalog.getAppCertCatalog(appId); byte[] pubKeyInfo = appsCert.getSubjectPublicKeyInfo().getEncoded(); si.setPublicKeyInfo(pubKeyInfo); // si.setPublicKeyInfo(publicKey); exCap.setSubjectInfo(si); // set validity condition (validity time) of the exCap ValidityCondition vc = new ValidityCondition(); Timestamp ts1 = new Timestamp(System.currentTimeMillis()); Timestamp ts2 = new Timestamp(System.currentTimeMillis() + VALIDITY_PERIOD); vc.setValidAfter(ts1.toString()); vc.setValidBefore(ts2.toString()); exCap.setValidityCondition(vc); AccessRights accessRights = new AccessRights(); AccessRight ar1 = new AccessRight(); ar1.setAccessType(AccessType.REALTIME_PULL); // create condition --> read from XML file log.info("Will read condition for access right from a file..."); // right now we assume only 1 condition exists final File conditionFolder = new File(conditionPath); for (File condFile : conditionFolder.listFiles()) { if (!condFile.isDirectory() && condFile.getName() != null && (condFile.getName().endsWith(".xml") || condFile.getName().endsWith(".xml"))) { ConditionType condition = CapabilityUtils.xmlToConditionType(condFile); ar1.setCondition(condition); } } accessRights.getAccessRight().add(ar1); exCap.setAccessRights(accessRights); log.info("The access rights have been set!!"); // creating digital signature String iiJson = CapToXmlUtils.createIssuerInfoXml(ii); String siJson = CapToXmlUtils.createSubjectInfoXml(si); String arJson = CapToXmlUtils.createAccessRightsXml(accessRights); String riJson = CapToXmlUtils.createResourceIdXml(thingServiceId); String vcJson = CapToXmlUtils.createValidityConditionXml(vc); String revUrlJson = CapToXmlUtils.createRevocationUrlXml(REVOCATION_URL); String capContents = iiJson + "," + siJson + "," + arJson + riJson + "," + vcJson + "," + revUrlJson; // set the digital signature byte[] sign = CapabilityUtils.createCapSignature(myCredential, capContents); exCap.setDigitalSignature(sign); log.info("The digital signature has been generated!!"); return exCap; }
From source file:eu.betaas.service.securitymanager.service.impl.AuthorizationService.java
License:Apache License
/** * Method to verify the token upon access request. * @param token: the required token to be verified (in JSON format) *//*from ww w. j a v a2s . co m*/ public boolean verifyToken(String token) throws JAXBException, IOException, OperatorException, CertException, CMSException { // boolean isValid = false; log.info("Start the token validation process..."); Token tokenRead = CapabilityUtils.xmlToToken(token); if (tokenRead != null) { for (CapabilityExternal cap : tokenRead.getCapability()) { // CapabilityExternal cap = CapabilityUtils.jsonToExCap(token); log.debug("Reading capability " + cap.getResourceId()); // issuer info IssuerInfo ii = cap.getIssuerInfo(); // subject info SubjectInfo si = cap.getSubjectInfo(); // access rights AccessRights ars = cap.getAccessRights(); // resource ID String resourceId = cap.getResourceId(); // validity condition ValidityCondition vc = cap.getValidityCondition(); // revocation URL String revocationUrl = cap.getRevocationUrl(); String iiJson = CapToXmlUtils.createIssuerInfoXml(ii); String siJson = CapToXmlUtils.createSubjectInfoXml(si); String arJson = CapToXmlUtils.createAccessRightsXml(ars); String riJson = CapToXmlUtils.createResourceIdXml(resourceId); String vcJson = CapToXmlUtils.createValidityConditionXml(vc); String revUrlJson = CapToXmlUtils.createRevocationUrlXml(revocationUrl); String capContents = iiJson + "," + siJson + "," + arJson + riJson + "," + vcJson + "," + revUrlJson; // decoding the issuer certificate from byte[] byte[] issuerCert = ii.getIssuerCertificate(); X509CertificateHolder cert = new X509CertificateHolder(issuerCert); // validate issuer certificate of the external capability if (!validateIssuerCert(cert, ii.getIssuerType())) { // log.error("The issuer certificate is NOT valid!!!"); return false; } // check validity condition if (!CapabilityUtils.checkValidityCondition(vc)) return false; // check the access rights // try { // if(!checkAccessRight(ars, resourceId, createReqCtx(resourceId))) // return false; // } catch (Exception e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // validating the Digital signature of External Capability AsymmetricKeyParameter pubKey = PublicKeyFactory.createKey(cert.getSubjectPublicKeyInfo()); if (!CapabilityUtils.validateCapSignature(capContents, cap.getDigitalSignature(), pubKey)) { return false; } log.info("Passed all the validation test.."); } } else { log.error("Error in parsing the token..."); return false; } log.debug("will return true..."); return true; }
From source file:eu.betaas.taas.securitymanager.authentication.service.impl.GWEcmqvExtService.java
License:Apache License
public EcmqvMessage initEcmqv(byte[] ephPubX, byte[] ephPubY, byte[] certByte) { // decode the certificate X509CertificateHolder cert = null; try {/*www. ja v a 2 s . c o m*/ cert = new X509CertificateHolder(certByte); } catch (IOException e1) { log.error("Error in decoding the submitted certificate!!"); e1.printStackTrace(); } // validate the certificate boolean isCertValid = false; try { isCertValid = validateCert(cert); } catch (Exception e) { log.error("Error in verifying the submitted certificate: " + e.getMessage()); e.printStackTrace(); } if (!isCertValid) { log.error("The submitted certificate is not valid!!"); return null; } log.debug("Passed the certificate validation!!"); // decode the ephemeral public key try { ephPub = ECKeyPairGen.generateECPublicKey192(new BigInteger(ephPubX), new BigInteger(ephPubY)); } catch (Exception e) { log.error("Error in decoding the submitted ephemeral public key: " + e.getMessage()); e.printStackTrace(); } // perform embedded public key validation boolean pubValid = ECMQVUtils.validateEmbedPubKey(ephPub); if (!pubValid) { log.error("The submitted ephemeral public key is not valid!!"); return null; } log.debug("Passed the embedded ephemeral public key validation!!"); // generates its own ephemeral key pairs, we assume that in this stage the // ephemeral key pairs were not generated AsymmetricCipherKeyPair myEphKp = ECKeyPairGen.generateECKeyPair192(); myEphPub = (ECPublicKeyParameters) myEphKp.getPublic(); myEphPriv = (ECPrivateKeyParameters) myEphKp.getPrivate(); // computes the implicit signature --> the static private key was obtained // when we validate the certificate (upon loading the KeyStore) BigInteger implSig = ECMQVUtils.computeImplicitSig(myEphPub, myEphPriv, statPriv); // calculates the shared key K ECPoint K = null; try { K = ECMQVUtils.calculateSharedKey(ephPub, (ECPublicKeyParameters) PublicKeyFactory.createKey(cert.getSubjectPublicKeyInfo()), ephPub.getParameters().getH(), implSig); } catch (IOException e) { log.error("Error in calculating the shared key K: " + e.getMessage()); e.printStackTrace(); } // derive 2 symmetric keys from the shared key K byte[] Kx = K.normalize().getXCoord().toBigInteger().toByteArray(); int Lx = K.normalize().getXCoord().toBigInteger().bitLength(); double x = Math.log(Lx) / Math.log(2.0); double L = Math.pow(2, 1 + Math.ceil(x)); byte[] deriveK = ECMQVUtils.deriveKeyHKDF(Kx, (int) L / 8); // k1 and k2 split from newKey --> k1: to be MACed, k2: the session key k1 = new byte[deriveK.length / 2]; k2 = new byte[deriveK.length / 2]; int c = 0; for (byte b : deriveK) { if (c < deriveK.length / 2) { k1[c] = b; } else { k2[c - deriveK.length / 2] = b; } c++; } // retrieving my user friendly name from the SubjectAlternativeNames in my // certificate Extensions myExs = myCert.getExtensions(); if (myExs != null) { GeneralNames gns = GeneralNames.fromExtensions(myExs, Extension.subjectAlternativeName); for (int i = 0; i < gns.getNames().length; i++) { myUFN = gns.getNames()[i].getName().toString(); } } // retrieving other GW user friendly name from the SubjectAlternativeNames // in the submitted certificate Extensions oExs = cert.getExtensions(); if (oExs != null) { GeneralNames gns = GeneralNames.fromExtensions(oExs, Extension.subjectAlternativeName); for (int i = 0; i < gns.getNames().length; i++) { ufn = gns.getNames()[i].getName().toString(); } } // compute the MAC to be sent to the other gateway byte[] myMac = ECMQVUtils.computeMAC("2", myUFN, ufn, myEphPub.getQ().getEncoded(), ephPub.getQ().getEncoded(), k1); EcmqvMessage eMsg = new EcmqvMessage(); eMsg.setMyMac(myMac); try { eMsg.setMyCertificate(myCert.getEncoded()); } catch (IOException e) { log.error("Error in encoding the certificate: " + e.getMessage()); e.printStackTrace(); } eMsg.setEphemeralPublicX(myEphPub.getQ().normalize().getXCoord().toBigInteger().toByteArray()); eMsg.setEphemeralPublicY(myEphPub.getQ().normalize().getXCoord().toBigInteger().toByteArray()); return eMsg; }
From source file:eu.betaas.taas.securitymanager.authentication.service.impl.GWEcmqvIntService.java
License:Apache License
public byte[] responseEcmqv(EcmqvMessage eMsg) throws Exception { // decode the certificate X509CertificateHolder cert = new X509CertificateHolder(eMsg.getMyCertificate()); // decode the ECPublicKey ECPublicKeyParameters ephPub = ECKeyPairGen.generateECPublicKey192( new BigInteger(eMsg.getEphemeralPublicX()), new BigInteger(eMsg.getEphemeralPublicY())); // get the MAC 2 byte[] mac2 = eMsg.getMyMac(); // validate the certificate boolean isCertValid = false; isCertValid = validateCert(cert);/*from w w w. jav a 2 s . c o m*/ if (!isCertValid) { log.error("The submitted certificate is not valid!!"); return null; } log.debug("Passed the certificate validation!!"); // perform embedded public key validation boolean pubValid = ECMQVUtils.validateEmbedPubKey(ephPub); if (!pubValid) { log.error("The submitted ephemeral public key is not valid!!"); return null; } log.debug("Passed the embedded ephemeral public key validation!!"); // set the ephPub with this received ephPub this.ephPub = ephPub; // now, no need to generate my own ephemeral key here, because it is done // compute the implicit signature BigInteger implSig = ECMQVUtils.computeImplicitSig(myEphPub, myEphPriv, statPriv); // calculates the shared key K ECPublicKeyParameters statPub = (ECPublicKeyParameters) PublicKeyFactory .createKey(cert.getSubjectPublicKeyInfo()); org.bouncycastle.math.ec.ECPoint K = ECMQVUtils.calculateSharedKey(this.ephPub, statPub, this.ephPub.getParameters().getH(), implSig); // derive 2 symmetric keys from the shared key K byte[] Kx = K.normalize().getXCoord().toBigInteger().toByteArray(); int Lx = K.normalize().getXCoord().toBigInteger().bitLength(); double x = Math.log(Lx) / Math.log(2.0); double L = Math.pow(2, 1 + Math.ceil(x)); byte[] deriveK = ECMQVUtils.deriveKeyHKDF(Kx, (int) L / 8); // k1 and k2 split from newKey --> k1: to be MACed, k2: the session key k1 = new byte[deriveK.length / 2]; k2 = new byte[deriveK.length / 2]; int c = 0; for (byte b : deriveK) { if (c < deriveK.length / 2) { k1[c] = b; } else { k2[c - deriveK.length / 2] = b; } c++; } // retrieving my user friendly name from the SubjectAlternativeNames in my // certificate Extensions myExs = myCert.getExtensions(); if (myExs != null) { GeneralNames gns = GeneralNames.fromExtensions(myExs, Extension.subjectAlternativeName); for (int i = 0; i < gns.getNames().length; i++) { myUFN = gns.getNames()[i].getName().toString(); } } // retrieving other GW user friendly name from the SubjectAlternativeNames // in the submitted certificate Extensions oExs = cert.getExtensions(); if (oExs != null) { GeneralNames gns = GeneralNames.fromExtensions(oExs, Extension.subjectAlternativeName); for (int i = 0; i < gns.getNames().length; i++) { ufn = gns.getNames()[i].getName().toString(); } } // validate MAC 2, which is received from other GW boolean isMac2Valid = verifyMac2(mac2, ufn, myUFN, this.ephPub, myEphPub, k1); // compute the MAC to be sent to the other gateway if (!isMac2Valid) { log.error("Fails to verify the received MAC (2)!!"); return null; } log.debug("Successfully verifies the received MAC (2)!!"); byte[] mac3 = ECMQVUtils.computeMAC("3", myUFN, ufn, myEphPub.getQ().getEncoded(), ephPub.getQ().getEncoded(), k1); return mac3; }
From source file:net.solarnetwork.pki.bc.BCCertificateService.java
License:Open Source License
@Override public String generatePKCS10CertificateRequestString(X509Certificate cert, PrivateKey privateKey) throws CertificateException { X509CertificateHolder holder; try {//from ww w .j a va 2 s . c om holder = new JcaX509CertificateHolder(cert); } catch (CertificateEncodingException e) { throw new CertificateException("Error creating CSR", e); } PKCS10CertificationRequestBuilder builder = new PKCS10CertificationRequestBuilder(holder.getSubject(), holder.getSubjectPublicKeyInfo()); JcaContentSignerBuilder signerBuilder = new JcaContentSignerBuilder(signatureAlgorithm); ContentSigner signer; try { signer = signerBuilder.build(privateKey); } catch (OperatorCreationException e) { throw new CertificateException("Error signing certificate request", e); } PKCS10CertificationRequest csr = builder.build(signer); StringWriter writer = new StringWriter(); PemWriter pemWriter = new PemWriter(writer); try { pemWriter.writeObject(new PemObject("CERTIFICATE REQUEST", csr.getEncoded())); } catch (IOException e) { throw new CertificateException("Error signing certificate", e); } finally { try { pemWriter.flush(); pemWriter.close(); writer.close(); } catch (IOException e) { // ignore this } } return writer.toString(); }
From source file:org.codice.ddf.security.certificate.generator.CertificateSigningRequestTest.java
License:Open Source License
@Test public void testNewCertificateBuilderWithoutSan() throws Exception { final DateTime start = DateTime.now().minusDays(1); final DateTime end = start.plusYears(100); final KeyPair kp = makeKeyPair(); csr.setSerialNumber(1);/*from www . ja v a 2 s . c o m*/ csr.setNotBefore(start); csr.setNotAfter(end); csr.setCommonName("A"); csr.setSubjectKeyPair(kp); final X509Certificate issuerCert = mock(X509Certificate.class); doReturn(new X500Principal("CN=Duke, OU=JavaSoft, O=Sun Microsystems, C=US")).when(issuerCert) .getSubjectX500Principal(); final JcaX509v3CertificateBuilder builder = csr.newCertificateBuilder(issuerCert); final X509CertificateHolder holder = builder.build(new DemoCertificateAuthority().getContentSigner()); assertThat(holder.getSerialNumber(), equalTo(BigInteger.ONE)); assertThat(holder.getNotBefore(), equalTo(new Time(start.toDate()).getDate())); assertThat(holder.getNotAfter(), equalTo(new Time(end.toDate()).getDate())); assertThat(holder.getSubject().toString(), equalTo("cn=A")); assertThat("Unable to validate public key", holder.getSubjectPublicKeyInfo(), equalTo(SubjectPublicKeyInfo.getInstance(kp.getPublic().getEncoded()))); assertThat("There should be no subject alternative name extension", holder.getExtension(org.bouncycastle.asn1.x509.Extension.subjectAlternativeName), nullValue(org.bouncycastle.asn1.x509.Extension.class)); }