List of usage examples for java.security GeneralSecurityException getMessage
public String getMessage()
From source file:pepperim.util.IMCrypt.java
/** * @param data Data to be verified// w w w . ja va 2 s .c o m * @param b64sig Base64-encoded RSA signature * @param key Public key of the signature source * @return true on success, false if the verification fails */ public static boolean RSA_Verify(String data, String b64sig, PublicKey key) { try { Signature verifier = Signature.getInstance("SHA1withRSA"); verifier.initVerify(key); verifier.update(data.getBytes()); return verifier.verify(B64_Dec(b64sig)); } catch (GeneralSecurityException e) { Main.log(e.getMessage()); return false; } }
From source file:pepperim.util.IMCrypt.java
/** * @param b64str Base64-encoded private key * @return PrivateKey object//from ww w. j a v a2s. co m */ public static PrivateKey decodePrivateKey(String b64str) { try { byte[] keydata = B64_Dec(b64str); PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(keydata); KeyFactory kf = KeyFactory.getInstance("RSA"); PrivateKey pk = kf.generatePrivate(ks); return pk; } catch (GeneralSecurityException e) { Main.log(e.getMessage()); return null; } }
From source file:pepperim.util.IMCrypt.java
/** * @param b64str Base64-encoded public key * @return PublicKey object/*from w w w . j a va 2s . c om*/ */ public static PublicKey decodePublicKey(String b64str) { try { byte[] keydata = B64_Dec(b64str); X509EncodedKeySpec ks = new X509EncodedKeySpec(keydata); KeyFactory kf = KeyFactory.getInstance("RSA"); PublicKey pk = kf.generatePublic(ks); return pk; } catch (GeneralSecurityException e) { Main.log(e.getMessage()); return null; } }
From source file:pepperim.util.IMCrypt.java
/** * Regular RSA signing (using SHA1-hash) * @param data Data to be signed// w w w . j a v a 2 s. c o m * @param key Key to be used for the signature * @return Base64-encoded RSA signature */ public static String RSA_Sign(String data, PrivateKey key) { try { Signature signer = Signature.getInstance("SHA1withRSA"); signer.initSign(key); signer.update(data.getBytes()); byte[] signature = signer.sign(); return B64_Enc(signature); } catch (GeneralSecurityException e) { Main.log(e.getMessage()); return ""; } }
From source file:pepperim.util.IMCrypt.java
/** * Generates a new 2048 bit RSA keypair. * @return String array containing: [Base64-encoded public key, Base64-encoded private key] *///from w ww .j ava 2 s.c o m public static String[] RSA_genKeypair() { try { KeyPairGenerator pairgen = KeyPairGenerator.getInstance("RSA"); SecureRandom random = new SecureRandom(); pairgen.initialize(2048, random); KeyPair keyPair = pairgen.generateKeyPair(); String[] keypair = new String[2]; keypair[0] = B64_Enc(keyPair.getPublic().getEncoded()); keypair[1] = B64_Enc(keyPair.getPrivate().getEncoded()); return keypair; } catch (GeneralSecurityException e) { Main.log(e.getMessage()); return null; } }
From source file:com.vmware.identity.idm.IDPConfig.java
/** * Validate the chain is in the required order user's certificate first, * root CA certificate last including the case of only root CA is present. * Also validate that there is only one chain, which consists of all the * certificates listed./*from w w w . j a va 2s . co m*/ */ private static boolean validateSingleX509CertChain(List<X509Certificate> chain) throws ExternalIDPExtraneousCertsInCertChainException, ExternalIDPCertChainInvalidTrustedPathException { final String ALGO_PKIX = "PKIX"; //for X.509 final String CERTSTORE_PROVIDER_COLLECTION = "Collection"; try { Set<TrustAnchor> anchors = new HashSet<TrustAnchor>(); anchors.add(new TrustAnchor(chain.get(chain.size() - 1), null)); X509CertSelector targetCertSelector = new X509CertSelector(); targetCertSelector.setCertificate(chain.get(0)); CertStore builderStore = CertStore.getInstance(CERTSTORE_PROVIDER_COLLECTION, new CollectionCertStoreParameters(chain)); PKIXBuilderParameters buildParams = new PKIXBuilderParameters(anchors, targetCertSelector); buildParams.addCertStore(builderStore); buildParams.setRevocationEnabled(false); CertPathBuilder pathBuilder = CertPathBuilder.getInstance(ALGO_PKIX); CertPathBuilderResult builderResult = pathBuilder.build(buildParams); if (chain.size() - 1 != builderResult.getCertPath().getCertificates().size()) { throw new ExternalIDPExtraneousCertsInCertChainException(chain); } return true; } catch (CertPathBuilderException cpbe) { throw new ExternalIDPCertChainInvalidTrustedPathException(cpbe.getMessage(), chain); // no need to chain the exception. } catch (GeneralSecurityException gse) { throw new ExternalIDPCertChainInvalidTrustedPathException(gse.getMessage(), chain); } }
From source file:password.pwm.util.secure.SecureEngine.java
private static byte[] computeHmacToBytes(final HmacAlgorithm hmacAlgorithm, final PwmSecurityKey pwmSecurityKey, final byte[] input) throws PwmUnrecoverableException { try {/*from w ww . j a v a 2 s . co m*/ final Mac mac = Mac.getInstance(hmacAlgorithm.getAlgorithmName()); final SecretKey secret_key = pwmSecurityKey.getKey(hmacAlgorithm.getKeyType()); mac.init(secret_key); return mac.doFinal(input); } catch (GeneralSecurityException e) { final String errorMsg = "error during hmac operation: " + e.getMessage(); final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_CRYPT_ERROR, errorMsg); throw new PwmUnrecoverableException(errorInformation); } }
From source file:helpers.Methods.java
public static void trustAllCertificates() { //Certification check // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { @Override/*from w w w . j ava 2s .c o m*/ public java.security.cert.X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } @Override public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) { } @Override public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) { } } }; // Install the all-trusting trust manager try { SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } catch (GeneralSecurityException ex) { Variables.logger.Log(Methods.class, Variables.LogType.Error, "Error in trusting all certificates. Details:\r\n" + ex.getMessage()); } }
From source file:at.alladin.rmbt.shared.Helperfunctions.java
public static String calculateHMAC(final String secret, final String data) { try {/* w w w. j a va 2 s.com*/ final SecretKeySpec signingKey = new SecretKeySpec(secret.getBytes(), "HmacSHA1"); final Mac mac = Mac.getInstance("HmacSHA1"); mac.init(signingKey); final byte[] rawHmac = mac.doFinal(data.getBytes()); final String result = new String(Base64.encodeBytes(rawHmac)); return result; } catch (final GeneralSecurityException e) { System.out.println("Unexpected error while creating hash: " + e.getMessage()); return ""; } }
From source file:com.cws.esolutions.security.utils.DAOInitializer.java
/** * @param properties - The <code>AuthRepo</code> object containing connection information * @param isContainer - A <code>boolean</code> flag indicating if this is in a container * @param bean - The {@link com.cws.esolutions.security.SecurityServiceBean} <code>SecurityServiceBean</code> that holds the connection * @throws SecurityServiceException {@link com.cws.esolutions.security.exception.SecurityServiceException} * if an exception occurs opening the connection *///from w ww . ja v a 2s . c o m public synchronized static void configureAndCreateAuthConnection(final InputStream properties, final boolean isContainer, final SecurityServiceBean bean) throws SecurityServiceException { String methodName = DAOInitializer.CNAME + "#configureAndCreateAuthConnection(final String properties, final boolean isContainer, final SecurityServiceBean bean) throws SecurityServiceException"; if (DEBUG) { DEBUGGER.debug(methodName); DEBUGGER.debug("InputStream: {}", properties); DEBUGGER.debug("isContainer: {}", isContainer); DEBUGGER.debug("SecurityServiceBean: {}", bean); } try { Properties connProps = new Properties(); connProps.load(properties); if (DEBUG) { DEBUGGER.debug("Properties: {}", connProps); } AuthRepositoryType repoType = AuthRepositoryType .valueOf(connProps.getProperty(DAOInitializer.REPO_TYPE)); RepositoryConnectionType connType = RepositoryConnectionType .valueOf(connProps.getProperty(DAOInitializer.CONN_TYPE)); if (DEBUG) { DEBUGGER.debug("AuthRepositoryType: {}", repoType); DEBUGGER.debug("RepositoryConnectionType: {}", connType); } switch (repoType) { case LDAP: SSLUtil sslUtil = null; LDAPConnection ldapConn = null; LDAPConnectionPool connPool = null; LDAPConnectionOptions connOpts = new LDAPConnectionOptions(); connOpts.setAutoReconnect(true); connOpts.setAbandonOnTimeout(true); connOpts.setBindWithDNRequiresPassword(true); connOpts.setConnectTimeoutMillis( Integer.parseInt(connProps.getProperty(DAOInitializer.CONN_TIMEOUT))); connOpts.setResponseTimeoutMillis( Integer.parseInt(connProps.getProperty(DAOInitializer.READ_TIMEOUT))); if (DEBUG) { DEBUGGER.debug("LDAPConnectionOptions: {}", connOpts); } switch (connType) { case CONNECTION_TYPE_INSECURE: ldapConn = new LDAPConnection(connOpts, connProps.getProperty(DAOInitializer.REPOSITORY_HOST), Integer.parseInt(connProps.getProperty(DAOInitializer.REPOSITORY_PORT))); if (DEBUG) { DEBUGGER.debug("LDAPConnection: {}", ldapConn); } if (!(ldapConn.isConnected())) { throw new LDAPException(ResultCode.CONNECT_ERROR, "Failed to establish an LDAP connection"); } connPool = new LDAPConnectionPool(ldapConn, Integer.parseInt(connProps.getProperty(DAOInitializer.MIN_CONNECTIONS)), Integer.parseInt(connProps.getProperty(DAOInitializer.MAX_CONNECTIONS))); break; case CONNECTION_TYPE_SSL: sslUtil = new SSLUtil(new TrustStoreTrustManager( connProps.getProperty(DAOInitializer.TRUST_FILE), PasswordUtils .decryptText(connProps.getProperty(DAOInitializer.TRUST_PASS), connProps.getProperty(DAOInitializer.TRUST_SALT), secConfig.getSecretAlgorithm(), secConfig.getIterations(), secConfig.getKeyBits(), secConfig.getEncryptionAlgorithm(), secConfig.getEncryptionInstance(), systemConfig.getEncoding()) .toCharArray(), connProps.getProperty(DAOInitializer.TRUST_TYPE), true)); if (DEBUG) { DEBUGGER.debug("SSLUtil: {}", sslUtil); } SSLSocketFactory sslSocketFactory = sslUtil.createSSLSocketFactory(); if (DEBUG) { DEBUGGER.debug("SSLSocketFactory: {}", sslSocketFactory); } ldapConn = new LDAPConnection(sslSocketFactory, connOpts, connProps.getProperty(DAOInitializer.REPOSITORY_HOST), Integer.parseInt(connProps.getProperty(DAOInitializer.REPOSITORY_PORT))); if (DEBUG) { DEBUGGER.debug("LDAPConnection: {}", ldapConn); } if (!(ldapConn.isConnected())) { throw new LDAPException(ResultCode.CONNECT_ERROR, "Failed to establish an LDAP connection"); } connPool = new LDAPConnectionPool(ldapConn, Integer.parseInt(connProps.getProperty(DAOInitializer.MIN_CONNECTIONS)), Integer.parseInt(connProps.getProperty(DAOInitializer.MAX_CONNECTIONS))); break; case CONNECTION_TYPE_TLS: ldapConn = new LDAPConnection(connOpts, connProps.getProperty(DAOInitializer.REPOSITORY_HOST), Integer.parseInt(connProps.getProperty(DAOInitializer.REPOSITORY_PORT))); if (DEBUG) { DEBUGGER.debug("LDAPConnection: {}", ldapConn); } if (!(ldapConn.isConnected())) { throw new LDAPException(ResultCode.CONNECT_ERROR, "Failed to establish an LDAP connection"); } sslUtil = new SSLUtil(new TrustStoreTrustManager( connProps.getProperty(DAOInitializer.TRUST_FILE), PasswordUtils .decryptText(connProps.getProperty(DAOInitializer.TRUST_PASS), connProps.getProperty(DAOInitializer.TRUST_SALT), secConfig.getSecretAlgorithm(), secConfig.getIterations(), secConfig.getKeyBits(), secConfig.getEncryptionAlgorithm(), secConfig.getEncryptionInstance(), systemConfig.getEncoding()) .toCharArray(), connProps.getProperty(DAOInitializer.TRUST_TYPE), true)); if (DEBUG) { DEBUGGER.debug("SSLUtil: {}", sslUtil); } SSLContext sslContext = sslUtil.createSSLContext(); if (DEBUG) { DEBUGGER.debug("SSLContext: {}", sslContext); } StartTLSExtendedRequest startTLS = new StartTLSExtendedRequest(sslContext); if (DEBUG) { DEBUGGER.debug("StartTLSExtendedRequest: {}", startTLS); } ExtendedResult extendedResult = ldapConn.processExtendedOperation(startTLS); if (DEBUG) { DEBUGGER.debug("ExtendedResult: {}", extendedResult); } BindRequest bindRequest = new SimpleBindRequest( connProps.getProperty(DAOInitializer.REPOSITORY_USER), PasswordUtils.decryptText(connProps.getProperty(DAOInitializer.TRUST_PASS), connProps.getProperty(DAOInitializer.TRUST_SALT), secConfig.getSecretAlgorithm(), secConfig.getIterations(), secConfig.getKeyBits(), secConfig.getEncryptionAlgorithm(), secConfig.getEncryptionInstance(), systemConfig.getEncoding())); if (DEBUG) { DEBUGGER.debug("BindRequest: {}", bindRequest); } BindResult bindResult = ldapConn.bind(bindRequest); if (DEBUG) { DEBUGGER.debug("BindResult: {}", bindResult); } StartTLSPostConnectProcessor tlsProcessor = new StartTLSPostConnectProcessor(sslContext); if (DEBUG) { DEBUGGER.debug("StartTLSPostConnectProcessor: {}", tlsProcessor); } connPool = new LDAPConnectionPool(ldapConn, Integer.parseInt(connProps.getProperty(DAOInitializer.MIN_CONNECTIONS)), Integer.parseInt(connProps.getProperty(DAOInitializer.MAX_CONNECTIONS)), tlsProcessor); break; } if (DEBUG) { DEBUGGER.debug("LDAPConnectionPool: {}", connPool); } if ((connPool == null) || (connPool.isClosed())) { throw new LDAPException(ResultCode.CONNECT_ERROR, "Failed to establish an LDAP connection"); } bean.setAuthDataSource(connPool); break; case SQL: // the isContainer only matters here if (isContainer) { Context initContext = new InitialContext(); Context envContext = (Context) initContext.lookup(DAOInitializer.DS_CONTEXT); bean.setAuthDataSource(envContext.lookup(DAOInitializer.REPOSITORY_HOST)); } else { BasicDataSource dataSource = new BasicDataSource(); dataSource.setInitialSize( Integer.parseInt(connProps.getProperty(DAOInitializer.MIN_CONNECTIONS))); dataSource .setMaxActive(Integer.parseInt(connProps.getProperty(DAOInitializer.MAX_CONNECTIONS))); dataSource.setDriverClassName(connProps.getProperty(DAOInitializer.CONN_DRIVER)); dataSource.setUrl(connProps.getProperty(DAOInitializer.REPOSITORY_HOST)); dataSource.setUsername(connProps.getProperty(DAOInitializer.REPOSITORY_USER)); dataSource.setPassword(PasswordUtils.decryptText( connProps.getProperty(DAOInitializer.REPOSITORY_PASS), connProps.getProperty(DAOInitializer.REPOSITORY_SALT), secConfig.getSecretAlgorithm(), secConfig.getIterations(), secConfig.getKeyBits(), secConfig.getEncryptionAlgorithm(), secConfig.getEncryptionInstance(), systemConfig.getEncoding())); bean.setAuthDataSource(dataSource); } break; case NONE: return; default: throw new SecurityServiceException("Unhandled ResourceType"); } } catch (LDAPException lx) { throw new SecurityServiceException(lx.getMessage(), lx); } catch (GeneralSecurityException gsx) { throw new SecurityServiceException(gsx.getMessage(), gsx); } catch (NamingException nx) { throw new SecurityServiceException(nx.getMessage(), nx); } catch (FileNotFoundException fnfx) { throw new SecurityServiceException(fnfx.getMessage(), fnfx); } catch (IOException iox) { throw new SecurityServiceException(iox.getMessage(), iox); } }