List of usage examples for java.security.cert X509Certificate getPublicKey
public abstract PublicKey getPublicKey();
From source file:mitm.common.tools.SMIME.java
private static void inspectSigned(SMIMESignedInspector inspector, String cerOut) throws Exception { System.err.println("=============================="); System.err.println("Signed message"); System.err.println();/* w w w. j av a2 s .c om*/ System.err.println("CMSVersion: " + inspector.getVersion()); System.err.println(); List<SignerInfo> signers = inspector.getSigners(); List<X509Certificate> certificates = inspector.getCertificates(); for (int i = 0; i < signers.size(); i++) { SignerInfo signer = signers.get(i); System.err.println("*** [Signer " + i + "] ***"); System.err.println(); System.err.println(signer); System.err.println(); dumpSMIMECapabilities(signer.getSignedAttributes()); CertSelector selector = signer.getSignerId().getSelector(); List<X509Certificate> signingCerts = CertificateUtils.getMatchingCertificates(certificates, selector); if (signingCerts.size() > 0) { /* there could be more certificates but get the first one */ X509Certificate certificate = signingCerts.get(0); try { if (signer.verify(certificate.getPublicKey())) { System.err.println("Verification OK."); } } catch (SignerInfoException e) { System.err.println("* WARNING: verification failed. Message: " + e.getMessage()); } } else { System.err.println("* WARNING: Signing certificate not found so unable to verify signature *"); } } System.err.println("=============================="); System.err.println("Certificates:"); System.err.println(); for (int i = 0; i < certificates.size(); i++) { X509Certificate certificate = certificates.get(i); System.err.println("*** Certificate " + i); System.err.println(); System.err.println(certificate); System.err.println(); try { System.err.println("Extra information:"); System.err.println(); X509CertificateInspector certInspector = new X509CertificateInspector(certificate); System.err.println("SubjectKeyIdentifier: " + certInspector.getSubjectKeyIdentifierHex()); System.err.println("Email: " + certInspector.getEmail()); System.err.println(); } catch (CertificateParsingException e) { logger.error("Error while parsing the certificate", e); } } if (cerOut != null) { File outfile = new File(cerOut); CertificateUtils.writeCertificates(certificates, new FileOutputStream(outfile)); } List<X509CRL> crls = inspector.getCRLs(); System.err.println("=============================="); System.err.println("CRLs:"); System.err.println(); for (int i = 0; i < crls.size(); i++) { X509CRL crl = crls.get(i); System.err.println("*** CRL " + i); System.err.println(); System.err.println(crl); System.err.println(); } System.err.println("*** Unsigned message:"); System.err.println(); inspector.getContentAsMimeMessage().writeTo(System.out); }
From source file:be.fedict.trust.TrustValidator.java
/** * Gives back the trust linker result of a verification of a self-signed * X509 certificate.//from ww w .java 2s. c o m * * @param certificate * the self-signed certificate to validate. * @return the validation result. */ public static TrustLinkerResult getSelfSignedResult(X509Certificate certificate) { if (false == certificate.getIssuerX500Principal().equals(certificate.getSubjectX500Principal())) { return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_TRUST, "root certificate should be self-signed: " + certificate.getSubjectX500Principal()); } try { certificate.verify(certificate.getPublicKey()); } catch (Exception e) { return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_SIGNATURE, "certificate signature error: " + e.getMessage()); } return new TrustLinkerResult(true); }
From source file:com.dbay.apns4j.tools.ApnsTools.java
public final static SocketFactory createSocketFactory(InputStream keyStore, String password, String keystoreType, String algorithm, String protocol) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableKeyException, KeyManagementException, CertificateExpiredException { char[] pwdChars = password.toCharArray(); KeyStore ks = KeyStore.getInstance(keystoreType); ks.load(keyStore, pwdChars);//w w w .ja v a 2s . c o m // ?? Enumeration<String> enums = ks.aliases(); String alias = ""; if (enums.hasMoreElements()) { alias = enums.nextElement(); } if (StringUtils.isNotEmpty(alias)) { X509Certificate certificate = (X509Certificate) ks.getCertificate(alias); if (null != certificate) { String type = certificate.getType(); int ver = certificate.getVersion(); String name = certificate.getSubjectDN().getName(); String serialNumber = certificate.getSerialNumber().toString(16); String issuerDN = certificate.getIssuerDN().getName(); String sigAlgName = certificate.getSigAlgName(); String publicAlgorithm = certificate.getPublicKey().getAlgorithm(); Date before = certificate.getNotBefore(); Date after = certificate.getNotAfter(); String beforeStr = DateFormatUtils.format(before, "yyyy-MM-dd HH:mm:ss"); String afterStr = DateFormatUtils.format(after, "yyyy-MM-dd HH:mm:ss"); // ?? long expire = DateUtil.getNumberOfDaysBetween(new Date(), after); if (expire <= 0) { if (LOG.isErrorEnabled()) { LOG.error( "?[{}], [{}], ?[{}], ??[{}], ?[{}], ??[{}], [{}], [{}][{}], ?[{}]", name, type, ver, serialNumber, issuerDN, sigAlgName, publicAlgorithm, beforeStr, afterStr, Math.abs(expire)); } throw new CertificateExpiredException("??[" + Math.abs(expire) + "]"); } if (LOG.isInfoEnabled()) { LOG.info( "?[{}], [{}], ?[{}], ??[{}], ?[{}], ??[{}], [{}], [{}][{}], ?[{}]?", name, type, ver, serialNumber, issuerDN, sigAlgName, publicAlgorithm, beforeStr, afterStr, expire); } } } KeyManagerFactory kf = KeyManagerFactory.getInstance(algorithm); kf.init(ks, pwdChars); TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm); tmf.init((KeyStore) null); SSLContext context = SSLContext.getInstance(protocol); context.init(kf.getKeyManagers(), tmf.getTrustManagers(), null); return context.getSocketFactory(); }
From source file:com.owncloud.android.utils.EncryptionUtils.java
/** * Encrypt string with RSA algorithm, ECB mode, OAEPWithSHA-256AndMGF1 padding * Asymmetric encryption, with private and public key * * @param string String to encrypt/*from www . j av a 2 s. c o m*/ * @param cert contains public key in it * @return encrypted string */ @RequiresApi(api = Build.VERSION_CODES.KITKAT) public static String encryptStringAsymmetric(String string, String cert) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, IOException, CertificateException { Cipher cipher = Cipher.getInstance(RSA_CIPHER); String trimmedCert = cert.replace("-----BEGIN CERTIFICATE-----\n", "") .replace("-----END CERTIFICATE-----\n", ""); byte[] encodedCert = trimmedCert.getBytes("UTF-8"); byte[] decodedCert = org.apache.commons.codec.binary.Base64.decodeBase64(encodedCert); CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); InputStream in = new ByteArrayInputStream(decodedCert); X509Certificate certificate = (X509Certificate) certFactory.generateCertificate(in); PublicKey realPublicKey = certificate.getPublicKey(); cipher.init(Cipher.ENCRYPT_MODE, realPublicKey); byte[] bytes = encodeStringToBase64Bytes(string); byte[] cryptedBytes = cipher.doFinal(bytes); return encodeBytesToBase64String(cryptedBytes); }
From source file:cl.nic.dte.util.XMLUtil.java
/** * Obtiene el certificado digital contenido en un nodo XML Sinature (<a * href="http://www.w3.org/TR/xmldsig-core/">http://www.w3.org/TR/xmldsig-core/</a>) * //from ww w. jav a2s. c o m * @param signature * el nodo con el tag <Signature>. * @return El certificado digital contenido en el <KeyInfo> o * <code>null</code> en caso que el <Signature> no contenga * tal información. */ @SuppressWarnings("unchecked") public static X509Certificate getCertificate(XMLSignature signature) { String alg = signature.getSignedInfo().getSignatureMethod().getAlgorithm(); KeyInfo kinf = signature.getKeyInfo(); // Check for keyinfo if (kinf == null) { return null; } PublicKey pKey = null; List<X509Certificate> x509 = new ArrayList<X509Certificate>(); // I look for the public key and the certificates for (XMLStructure xst : (List<XMLStructure>) kinf.getContent()) { if (xst instanceof KeyValue) { PublicKey pk; try { pk = ((KeyValue) xst).getPublicKey(); if (algEquals(alg, pk.getAlgorithm())) pKey = pk; } catch (KeyException e) { // nothing } } if (xst instanceof X509Data) { for (Object cont : ((X509Data) xst).getContent()) if (cont instanceof X509Certificate) x509.add((X509Certificate) cont); } } // return of the certificates that matchs the public key. for (X509Certificate cert : x509) { if (cert.getPublicKey().equals(pKey)) { return cert; } } return null; }
From source file:net.sf.keystore_explorer.crypto.x509.X509CertUtil.java
/** * Verify that one X.509 certificate was signed using the private key that * corresponds to the public key of a second certificate. * * @return True if the first certificate was signed by private key * corresponding to the second signature * @param signedCert/*from w ww . j a v a2 s. c om*/ * The signed certificate * @param signingCert * The signing certificate * @throws CryptoException * If there was a problem verifying the signature. */ public static boolean verifyCertificate(X509Certificate signedCert, X509Certificate signingCert) throws CryptoException { try { signedCert.verify(signingCert.getPublicKey()); return true; } // Verification failed catch (InvalidKeyException ex) { return false; } catch (SignatureException ex) { return false; } // Problem verifying catch (NoSuchProviderException ex) { throw new CryptoException(res.getString("NoVerifyCertificate.exception.message"), ex); } catch (NoSuchAlgorithmException ex) { throw new CryptoException(res.getString("NoVerifyCertificate.exception.message"), ex); } catch (CertificateException ex) { throw new CryptoException(res.getString("NoVerifyCertificate.exception.message"), ex); } }
From source file:com.wandrell.example.swss.test.util.factory.SecureSoapMessages.java
private static final XMLSignature getSignature(final Document doc, final String BaseURI, final X509Certificate cert, final PrivateKey privateKey) throws XMLSecurityException { final XMLSignature sig; sig = new XMLSignature(doc, BaseURI, XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1); Transforms transforms = new Transforms(doc); transforms.addTransform(Transforms.TRANSFORM_C14N_OMIT_COMMENTS); // Sign the content of SOAP Envelope sig.addDocument("", transforms, Constants.ALGO_ID_DIGEST_SHA1); sig.addKeyInfo(cert);/*w w w . ja v a 2 s . c o m*/ sig.addKeyInfo(cert.getPublicKey()); sig.sign(privateKey); return sig; }
From source file:com.bernardomg.example.swss.test.util.factory.SecureSoapMessages.java
private static final XMLSignature getSignature(final Document doc, final String BaseURI, final X509Certificate cert, final PrivateKey privateKey) throws XMLSecurityException { final XMLSignature sig; sig = new XMLSignature(doc, BaseURI, XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1); final Transforms transforms = new Transforms(doc); transforms.addTransform(Transforms.TRANSFORM_C14N_OMIT_COMMENTS); // Sign the content of SOAP Envelope sig.addDocument("", transforms, Constants.ALGO_ID_DIGEST_SHA1); sig.addKeyInfo(cert);//from w w w .j av a2 s .com sig.addKeyInfo(cert.getPublicKey()); sig.sign(privateKey); return sig; }
From source file:Main.java
/** * Firma digitalmente usando la forma "enveloped signature" según el * estándar de la W3C (<a/*from w ww . ja v a2 s . co m*/ * href="http://www.w3.org/TR/xmldsig-core/">http://www.w3.org/TR/xmldsig-core/</a>). * <p> * * Este método además incorpora la información del * certificado a la sección <KeyInfo> opcional del * estándar, según lo exige SII. * <p> * * @param doc * El documento a firmar * @param uri * La referencia dentro del documento que debe ser firmada * @param pKey * La llave privada para firmar * @param cert * El certificado digital correspondiente a la llave privada * @throws NoSuchAlgorithmException * Si el algoritmo de firma de la llave no está soportado * (Actualmente soportado RSA+SHA1, DSA+SHA1 y HMAC+SHA1). * @throws InvalidAlgorithmParameterException * Si los algoritmos de canonización (parte del * estándar XML Signature) no son soportados (actaulmente * se usa el por defecto) * @throws KeyException * Si hay problemas al incluir la llave pública en el * <KeyValue>. * @throws MarshalException * @throws XMLSignatureException * * @see javax.xml.crypto.dsig.XMLSignature#sign(javax.xml.crypto.dsig.XMLSignContext) */ public static void signEmbeded(Node doc, String uri, PrivateKey pKey, X509Certificate cert) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, KeyException, MarshalException, XMLSignatureException { // Create a DOM XMLSignatureFactory that will be used to generate the // enveloped signature XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM"); // Create a Reference to the enveloped document (in this case we are // signing the whole document, so a URI of "" signifies that) and // also specify the SHA1 digest algorithm and the ENVELOPED Transform. Reference ref = fac.newReference(uri, fac.newDigestMethod(DigestMethod.SHA1, null), Collections.singletonList(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)), null, null); // Create the SignedInfo String method = SignatureMethod.RSA_SHA1; // default by SII if ("DSA".equals(cert.getPublicKey().getAlgorithm())) method = SignatureMethod.DSA_SHA1; else if ("HMAC".equals(cert.getPublicKey().getAlgorithm())) method = SignatureMethod.HMAC_SHA1; SignedInfo si = fac.newSignedInfo(fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, // Default canonical and // default by SII (C14NMethodParameterSpec) null), fac.newSignatureMethod(method, null), Collections.singletonList(ref)); KeyInfoFactory kif = fac.getKeyInfoFactory(); KeyValue kv = kif.newKeyValue(cert.getPublicKey()); // Create a KeyInfo and add the KeyValue to it List<XMLStructure> kidata = new ArrayList<XMLStructure>(); kidata.add(kv); kidata.add(kif.newX509Data(Collections.singletonList(cert))); KeyInfo ki = kif.newKeyInfo(kidata); // Create a DOMSignContext and specify the PrivateKey and // location of the resulting XMLSignature's parent element DOMSignContext dsc = new DOMSignContext(pKey, doc); // Create the XMLSignature (but don't sign it yet) XMLSignature signature = fac.newXMLSignature(si, ki); // Marshal, generate (and sign) the enveloped signature signature.sign(dsc); }
From source file:be.fedict.eid.dss.model.bean.AdministratorManagerBean.java
private String getId(X509Certificate certificate) { PublicKey publicKey = certificate.getPublicKey(); String id = DigestUtils.shaHex(publicKey.getEncoded()); return id;// w w w. ja v a 2 s. c o m }