List of usage examples for java.security.cert Certificate getPublicKey
public abstract PublicKey getPublicKey();
From source file:com.mqm.frame.infrastructure.util.ValidateLicense.java
/** * License// w ww . j a v a2s . com * * @param licenseColl LicenseColl * @param path String * @return boolean */ public static boolean validateLicense(LicenseColl licenseColl, String path) { // ?? boolean payedUser = true; List<String> macAddressList = CollectMacAddress.getMacAddress(); for (LicenseInfo licenseInfo : licenseColl.getLicenseInfoList()) { String productName = licenseInfo.getProductName(); String expirationDate = licenseInfo.getExpiration(); String signature = licenseInfo.getSignature(); boolean flag = false; String data = new StringBuffer().append(productName).append(expirationDate).toString(); java.security.cert.CertificateFactory cf; try { cf = java.security.cert.CertificateFactory.getInstance("X.509"); java.security.cert.Certificate cert = cf .generateCertificate(new FileInputStream(path + "/WEB-INF/fbrp.cer")); // PublicKey pubKey = cert.getPublicKey(); // ??Signature Signature sig = Signature.getInstance("SHA1withDSA"); sig.initVerify(pubKey); sig.update(InternationalizationUtil.getBytes(data)); // ?License boolean verifies = sig.verify(Base64.decode((InternationalizationUtil.getBytes(signature)))); if (verifies) { Date evalDate = DateTimeUtil.parseDate(expirationDate); if (evalDate.before(new Date())) { // ? payedUser = false; } else { flag = true; payedUser = true; System.out.println( "" + productName + " License" + expirationDate + "?"); } } } catch (Exception e) { log.error("", e); } if (!flag) { payedUser = false; System.out.println( "" + productName + " License??License?"); } } return payedUser; }
From source file:org.bankinterface.util.KeyStoreUtil.java
public static String pemToPkHex(String certString) throws IOException, CertificateException { Certificate cert = pemToCert(certString); return Hex.encodeHex(cert.getPublicKey().getEncoded()).toString(); }
From source file:kr.co.exsoft.eframework.util.LicenseUtil.java
/** * //from ww w.j ava2s .c o m * <pre> * 1. : ?? WAS * 2. : * </pre> * @Method Name : decipherLicenseKeyWeb * @param licenseKey * @return String * @throws Exception */ public static String decipherLicenseKeyWeb(String licenseKey) throws Exception { String ret = null; if (StringUtils.isNotBlank(licenseKey)) { // URLDecoder - ? ? String certName = URLDecoder.decode( LicenseUtil.class.getResource("/").getPath() + "kr/co/exsoft/eframework/cert/exsoft.cer", "utf-8"); // WAS if (certName.indexOf("WEB-INF/") != -1) { certName = certName.replace("WEB-INF", "WEB-INF/"); } FileInputStream certfis = null; try { certfis = new FileInputStream(certName); } catch (Exception e) { // JBOSS? Jboss system property? . // Jboss system ? standalone.xml ? /*<system-properties> <property name="org.apache.catalina.connector.URI_ENCODING" value="UTF-8" /> <property name="org.apache.catalina.connector.USE_BODY_ENCODING_FOR_QUERY_STRING" value="true" /> <property name="exsoft.license.cert.path" value="D:/jboss-eap-6.3/standalone/deployments/EDMS3.0.war/WEB-INF/classes" /> </system-properties>*/ // Jboss exception ? WAS System property certName = URLDecoder.decode( System.getProperty("exsoft.license.cert.path") + "/kr/co/exsoft/eframework/cert/exsoft.cer", "utf-8"); try { certfis = new FileInputStream(certName); } catch (Exception e2) { e2.printStackTrace(); } } CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate cert = cf.generateCertificate(certfis); PublicKey key = cert.getPublicKey(); // ?? . ret = unspell(licenseKey, key); } return ret; }
From source file:com.glaf.core.security.SecurityUtils.java
/** * ?????,??//from www . j a va 2 s. c om * * @param ctx * * @param symmetryKey * * @param pubKey * * @return String(?base64?) */ public static String generateDigitalEnvelope(SecurityContext ctx, Key symmetryKey, byte[] pubKey) { String result = null; InputStream inputStream = null; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); inputStream = new ByteArrayInputStream(pubKey); java.security.cert.Certificate cert = cf.generateCertificate(inputStream); inputStream.close(); PublicKey publicKey = cert.getPublicKey(); Cipher cipher = Cipher.getInstance(ctx.getAsymmetryAlgorithm()); cipher.init(Cipher.ENCRYPT_MODE, publicKey); result = Base64.encodeBase64String(cipher.doFinal(symmetryKey.getEncoded())); return result; } catch (Exception ex) { throw new SecurityException(ex); } finally { try { if (inputStream != null) { inputStream.close(); inputStream = null; } } catch (IOException ex) { } } }
From source file:net.sf.keystore_explorer.crypto.keystore.KeyStoreUtil.java
/** * Is the key pair entry identified by alias a EC key pair? * * @param alias//from w ww .java 2s .co m * Alias of key pair entry * @param keyStore * KeyStore that contains the key pair * @return True, if alias is a EC key pair * @throws KeyStoreException * If there was a problem accessing the KeyStore. */ public static boolean isECKeyPair(String alias, KeyStore keyStore) throws KeyStoreException { if (!isKeyPairEntry(alias, keyStore)) { return false; } Certificate certificate = keyStore.getCertificate(alias); String algorithm = certificate.getPublicKey().getAlgorithm(); return algorithm.equals(EC.jce()); }
From source file:net.sf.jsignpdf.utils.KeyStoreUtils.java
/** * Returns true if the given certificate can be used for encryption, false * otherwise./*from w ww . ja v a 2 s . c o m*/ * * @param cert * @return */ public static boolean isEncryptionSupported(final Certificate cert) { boolean result = false; if (cert != null) { try { Cipher.getInstance(cert.getPublicKey().getAlgorithm()); result = true; } catch (Exception e) { LOGGER.debug("Not possible to encrypt with the certificate", e); } } return result; }
From source file:org.dspace.authenticate.X509Authentication.java
/** * Verify CERTIFICATE against KEY. Return true if and only if CERTIFICATE is * valid and can be verified against KEY. * * @param context//from w ww . j ava 2 s . c om * The current DSpace context * @param certificate - * An X509 certificate object * @return - True if CERTIFICATE is valid and can be verified against KEY, * false otherwise. */ private static boolean isValid(Context context, X509Certificate certificate) { if (certificate == null) { return false; } // This checks that current time is within cert's validity window: try { certificate.checkValidity(); } catch (CertificateException e) { log.info(LogManager.getHeader(context, "authentication", "X.509 Certificate is EXPIRED or PREMATURE: " + e.toString())); return false; } // Try CA public key, if available. if (caPublicKey != null) { try { certificate.verify(caPublicKey); return true; } catch (GeneralSecurityException e) { log.info(LogManager.getHeader(context, "authentication", "X.509 Certificate FAILED SIGNATURE check: " + e.toString())); } } // Try it with keystore, if available. if (caCertKeyStore != null) { try { Enumeration ke = caCertKeyStore.aliases(); while (ke.hasMoreElements()) { String alias = (String) ke.nextElement(); if (caCertKeyStore.isCertificateEntry(alias)) { Certificate ca = caCertKeyStore.getCertificate(alias); try { certificate.verify(ca.getPublicKey()); return true; } catch (CertificateException ce) { } } } log.info(LogManager.getHeader(context, "authentication", "Keystore method FAILED SIGNATURE check on client cert.")); } catch (GeneralSecurityException e) { log.info(LogManager.getHeader(context, "authentication", "X.509 Certificate FAILED SIGNATURE check: " + e.toString())); } } return false; }
From source file:org.signserver.server.cryptotokens.CryptoTokenHelper.java
/** * Checks that the supplied certificate has a public key matching the * exiting one in the keystore.//from ww w.j a v a 2s.c om * @param keyStore to get the current public key from * @param alias of the entry to check * @param newCertificate to compare with the current one * @throws KeyStoreException if the keystore has not been initialized * @throws CryptoTokenOfflineException in case the keys does not match */ public static void ensureNewPublicKeyMatchesOld(KeyStore keyStore, String alias, Certificate newCertificate) throws KeyStoreException, CryptoTokenOfflineException { Certificate oldCert = keyStore.getCertificate(alias); if (!oldCert.getPublicKey().equals(newCertificate.getPublicKey())) { throw new CryptoTokenOfflineException("New certificate public key does not match current one"); } }
From source file:com.bcmcgroup.flare.client.ClientUtil.java
/** * Fetch a public key (certificate) from KeyStore * * @param keyStorePath a String containing the path to the KeyStore * @param keyStorePW a String containing the KeyStore password * @param alias a String containing the alias of targeted certificate * @return the PublicKey object containing the targeted public key * */// www .j a v a 2s. c o m public static PublicKey getPublicKeyByAlias(String keyStorePath, String keyStorePW, String alias) { KeyStore ks; FileInputStream is = null; try { ks = KeyStore.getInstance("JKS"); is = new FileInputStream(keyStorePath); ks.load(is, keyStorePW.toCharArray()); Certificate certificate = ks.getCertificate(alias); if (certificate != null) { return certificate.getPublicKey(); } } catch (FileNotFoundException e) { logger.error("FileNotFoundException when attempting to extract a public key by an alias in a keystore. " + e); } catch (IOException e) { logger.error("IOException when attempting to extract a public key by an alias in a keystore. " + e); } catch (KeyStoreException e) { logger.error( "KeyStoreException when attempting to extract a public key by an alias in a keystore. " + e); } catch (NoSuchAlgorithmException e) { logger.error( "NoSuchAlgorithmException when attempting to extract a public key by an alias in a keystore. " + e); } catch (CertificateException e) { logger.error( "CertificateException when attempting to extract a public key by an alias in a keystore. " + e); } finally { if (is != null) { try { is.close(); } catch (IOException ioe) { logger.error("IOException when attempting to close an input stream. " + ioe); } } } return null; }
From source file:org.signserver.server.cryptotokens.CryptoTokenHelper.java
/** * Performs test signatures for the specified keys or for all if "all" specified. * @param keyStore Loaded keystore to read keys from * @param alias Alias of key to test or "all" to test all * @param authCode Key password (if used, ie for JKS only) * @param signatureProvider Provider for creating the signature * @return The results for each key found * @throws CryptoTokenOfflineException In case the key could not be used *///from w w w . j a v a2 s .c om public static Collection<KeyTestResult> testKey(KeyStore keyStore, String alias, char[] authCode, String signatureProvider) throws CryptoTokenOfflineException { if (LOG.isDebugEnabled()) { LOG.debug("testKey for alias: " + alias); } final Collection<KeyTestResult> result = new LinkedList<KeyTestResult>(); try { final Enumeration<String> e = keyStore.aliases(); while (e.hasMoreElements()) { final String keyAlias = e.nextElement(); if (alias.equalsIgnoreCase(ICryptoToken.ALL_KEYS) || alias.equals(keyAlias)) { if (LOG.isDebugEnabled()) { LOG.debug("checking keyAlias: " + keyAlias); } if (keyStore.isKeyEntry(keyAlias)) { String status; String publicKeyHash = null; boolean success = false; try { final PrivateKey privateKey = (PrivateKey) keyStore.getKey(keyAlias, authCode); final Certificate entryCert = keyStore.getCertificate(keyAlias); if (entryCert != null) { final PublicKey publicKey = entryCert.getPublicKey(); publicKeyHash = createKeyHash(publicKey); testSignAndVerify(privateKey, publicKey, signatureProvider); success = true; status = ""; } else { status = "Not testing keys with alias " + keyAlias + ". No certificate exists."; } } catch (ClassCastException ce) { status = "Not testing keys with alias " + keyAlias + ". Not a private key."; } catch (InvalidKeyException ex) { LOG.error("Error testing key: " + keyAlias, ex); status = ex.getMessage(); } catch (KeyStoreException ex) { LOG.error("Error testing key: " + keyAlias, ex); status = ex.getMessage(); } catch (NoSuchAlgorithmException ex) { LOG.error("Error testing key: " + keyAlias, ex); status = ex.getMessage(); } catch (NoSuchProviderException ex) { LOG.error("Error testing key: " + keyAlias, ex); status = ex.getMessage(); } catch (SignatureException ex) { LOG.error("Error testing key: " + keyAlias, ex); status = ex.getMessage(); } catch (UnrecoverableKeyException ex) { LOG.error("Error testing key: " + keyAlias, ex); status = ex.getMessage(); } result.add(new KeyTestResult(keyAlias, success, status, publicKeyHash)); } } } } catch (KeyStoreException ex) { throw new CryptoTokenOfflineException(ex); } if (LOG.isDebugEnabled()) { LOG.debug("<testKey"); } return result; }