List of usage examples for org.bouncycastle.jce.provider BouncyCastleProvider BouncyCastleProvider
public BouncyCastleProvider()
From source file:com.skplanet.jose.jwa.crypto.CryptoUtils.java
License:Open Source License
public static ECPublicKey generateEcPublicKey(byte[] x, byte[] y) throws Exception { ECPublicKey publicKey = null; ECPublicKeySpec ecPublicKeySpec = new ECPublicKeySpec(new ECPoint(new BigInteger(x), new BigInteger(y)), P256);/* www. j a v a 2 s .co m*/ try { KeyFactory keyFactory = KeyFactory.getInstance("EC"); publicKey = (ECPublicKey) keyFactory.generatePublic(ecPublicKeySpec); } catch (NoSuchAlgorithmException e) { if (Security.getProvider("BC") == null) { Security.addProvider(new BouncyCastleProvider()); } KeyFactory keyFactory = KeyFactory.getInstance("EC", "BC"); publicKey = (ECPublicKey) keyFactory.generatePublic(ecPublicKeySpec); } return publicKey; }
From source file:com.soffid.iam.addons.federation.service.FederacioServiceImpl.java
@Override protected String handleGeneratePKCS10(FederationMember federationMember) throws Exception { FederationMember fm = federationMember; if (fm.getPrivateKey() == null || "".equals(fm.getPrivateKey().trim()) || fm.getPublicKey() == null //$NON-NLS-1$ || "".equals(fm.getPublicKey().trim())) { //$NON-NLS-1$ throw new Exception(Messages.getString("FederacioServiceImpl.MakePKCS10Message")); //$NON-NLS-1$ }/*from ww w. ja va2 s .c o m*/ java.security.PrivateKey _privateKey = null; java.security.PublicKey _publicKey = null; try { java.security.Security.addProvider(new BouncyCastleProvider()); } catch (Throwable th) { } java.io.StringReader srpr = new java.io.StringReader(fm.getPrivateKey()); org.bouncycastle.openssl.PEMReader prpr = new org.bouncycastle.openssl.PEMReader(srpr); Object prKey = prpr.readObject(); if (prKey instanceof java.security.KeyPair) { java.security.KeyPair kp = ((java.security.KeyPair) prKey); _privateKey = kp.getPrivate(); } else if (prKey instanceof java.security.PrivateKey) { _privateKey = (PrivateKey) prKey; } java.io.StringReader srpu = new java.io.StringReader(fm.getPublicKey()); org.bouncycastle.openssl.PEMReader prpu = new org.bouncycastle.openssl.PEMReader(srpu); Object pubKey = prpu.readObject(); if (pubKey instanceof java.security.KeyPair) { java.security.KeyPair kp = ((java.security.KeyPair) pubKey); _publicKey = kp.getPublic(); } else if (pubKey instanceof java.security.PublicKey) { _publicKey = (PublicKey) pubKey; } org.bouncycastle.jce.PKCS10CertificationRequest pkcs10 = new org.bouncycastle.jce.PKCS10CertificationRequest( "SHA1withRSA", //$NON-NLS-1$ new javax.security.auth.x500.X500Principal( "CN=" + fm.getPublicId() + ",OU=" + fm.getEntityGroup().getName()), //$NON-NLS-1$ //$NON-NLS-2$ _publicKey, null, _privateKey, "SunRsaSign"); //$NON-NLS-1$ return new String(es.caib.seycon.util.Base64.encodeBytes(pkcs10.getEncoded())); }
From source file:com.sparkred.crypto.CryptoEngine.java
/** * Do start service./*from www .jav a 2s. com*/ * * @throws ServiceException * the service exception * @see atg.nucleus.GenericService#doStartService() */ @Override public void doStartService() throws ServiceException { // Validate required properties if (getCryptoRepository() == null) { if (isLoggingError()) { logError("CryptoEngine.doStartService: " + "CryptoRepository was null."); } throw new ServiceException("CryptoRepository was null."); } if (getCryptoEngineIdentifier() == null) { if (isLoggingError()) { logError("CryptoEngine.doStartService: " + "CryptoEngineIdentifier was null."); } throw new ServiceException("CryptoEngineIdentifier was null."); } if (getKeyPassphrase() == null) { if (isLoggingError()) { logError("CryptoEngine.doStartService: " + "KeyPassphrase was null."); } throw new ServiceException("KeyPassphrase was null."); } // Add the BouncyCastle JCE Security provider Security.addProvider(new BouncyCastleProvider()); try { // Load this crypo engine's encrypted data passphrase RepositoryItem cryptoEngineItem = getCryptoRepository().getItem(getCryptoEngineIdentifier(), CryptoConstants.CRYPTO_ENGINE_ITEM_DESC); if (cryptoEngineItem == null) { if (isLoggingWarning()) { logWarning("CryptoEngine.doStartService: " + "This Crypto Engine has not yet been initialized. Initializing it now."); } initializeNewEngine(); cryptoEngineItem = getCryptoRepository().getItem(getCryptoEngineIdentifier(), CryptoConstants.CRYPTO_ENGINE_ITEM_DESC); } String encryptedDataPassphrase = (String) cryptoEngineItem .getPropertyValue(CryptoConstants.ENC_DATA_KEY_PROP_NAME); // Decrypt the data passphrase using the key passphrase final StandardPBEStringEncryptor dataPassDecryptor = new StandardPBEStringEncryptor(); dataPassDecryptor.setProviderName(CryptoConstants.BOUNCY_CASTLE_PROVIDER_NAME); dataPassDecryptor.setAlgorithm(CryptoConstants.STRONG_ALGO); dataPassDecryptor.setPassword(getKeyPassphrase()); String dataPassphrase = dataPassDecryptor.decrypt(encryptedDataPassphrase); if (isLoggingInfo()) { logInfo("CryptoEngine.doStartService: " + "dataPassphrase is: " + dataPassphrase); } // Setup the encryptor this.mEncryptor = new StandardPBEStringEncryptor(); this.mEncryptor.setProviderName(CryptoConstants.BOUNCY_CASTLE_PROVIDER_NAME); this.mEncryptor.setAlgorithm(CryptoConstants.STRONG_ALGO); this.mEncryptor.setPassword(dataPassphrase); } catch (Exception e) { if (isLoggingError()) { logError("CryptoEngine.doStartService: " + "Exception caught setting up the encryptor.", e); } } // Setup scheduled job to check the key expiration status ScheduledJob job = new ScheduledJob("SR:Crypto:" + getCryptoEngineIdentifier(), "Checks the key expiration status for the Spark::red encryptor: " + getCryptoEngineIdentifier(), getAbsoluteName(), getSchedule(), this, ScheduledJob.SCHEDULER_THREAD); setJobId(getScheduler().addScheduledJob(job)); }
From source file:com.sparkred.crypto.tools.RekeyEngine.java
/** * Initializes the decryptMethod, generates a new data passphrase, and sets up the local encryptor component. * * @throws SecurityException//from w w w . j a v a 2 s . c o m * the security exception * @throws NoSuchMethodException * the no such method exception */ private void initialize() throws SecurityException, NoSuchMethodException { if (isLoggingDebug()) { logDebug("RekeyEngine.initialize:" + "starting...."); } // Add the BouncyCastle JCE Security provider Security.addProvider(new BouncyCastleProvider()); // Generate new data passphrase this.mNewDataPassphrase = generateNewDataPassphrase(); if (isLoggingDebug()) { logDebug("RekeyEngine.initialize:" + "new data passphrase was generated:" + this.mNewDataPassphrase); } // Setup the decryptor Class[] decryptMethodArgs = new Class[1]; decryptMethodArgs[0] = String.class; Method decryptMethod = getDecryptorComponent().getClass().getMethod(getDecryptorMethod(), decryptMethodArgs); this.mDecryptMethod = decryptMethod; if (isLoggingDebug()) { logDebug("RekeyEngine.initialize:" + "decryptMethod is setup."); } // Setup the encryptor StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor(); encryptor.setProviderName(CryptoConstants.BOUNCY_CASTLE_PROVIDER_NAME); encryptor.setAlgorithm(CryptoConstants.STRONG_ALGO); encryptor.setPassword(this.mNewDataPassphrase); this.mEncryptor = encryptor; if (isLoggingDebug()) { logDebug("RekeyEngine.initialize:" + "encryptor is setup."); } }
From source file:com.spotify.sshagenttls.X509CertKeyCreator.java
License:Apache License
private static KeyPair generateRandomKeyPair() throws NoSuchAlgorithmException, NoSuchProviderException { Security.addProvider(new BouncyCastleProvider()); final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", "BC"); keyPairGenerator.initialize(KEY_SIZE, new SecureRandom()); return keyPairGenerator.generateKeyPair(); }
From source file:com.square.adherent.noyau.util.PasswordUtil.java
License:Open Source License
/** * Constructeur./* ww w .j av a 2s .com*/ * @param encryptorPassword le mot de passe utiliser pour l'encrypteur * @param encryptorAlgorithm l'algorithm d'encryption */ public PasswordUtil(String encryptorPassword, String encryptorAlgorithm) { encryptor = new StandardPBEStringEncryptor(); encryptor.setProvider(new BouncyCastleProvider()); encryptor.setAlgorithm(encryptorAlgorithm); encryptor.setPassword(encryptorPassword); }
From source file:com.sshtools.common.globusonlinetool.CredentialHelper.java
License:Open Source License
public static X509Credential createProxyFromPKCS12(String password, GSIConstants.CertificateType proxyType, int lifetimeHours, String pcksCert) throws Exception { X509Credential proxy = null;// w ww . jav a2 s. c o m KeyStore store; File keyfile = new File(pcksCert); Security.addProvider(new BouncyCastleProvider()); store = KeyStore.getInstance("PKCS12", "BC"); FileInputStream in = new FileInputStream(keyfile); try { store.load(in, password.toCharArray()); } catch (IOException ioe) { if (ioe.getMessage().indexOf("Illegal key size") >= 0) { throw new Exception( "GSI Exception: To use this PKCS#12 file you need to install the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files"); } else { throw new Exception("Wrong password or other security error"); } } Enumeration e = store.aliases(); Key key = null; java.security.cert.Certificate cert = null; if (!e.hasMoreElements()) { throw new Exception("GSI Exception: Could not access your certificate: No certificates found in file '" + pcksCert + "'"); } else { while (e.hasMoreElements()) { String alias = (String) e.nextElement(); key = store.getKey(alias, password.toCharArray()); if (key != null && (key instanceof PrivateKey)) { cert = store.getCertificate(alias); break; } } } if (!(cert instanceof X509Certificate)) { throw new Exception("GSI Exception: Could not access your certificate: bad certificate type."); } if (!(key instanceof PrivateKey)) { throw new Exception("GSI Exception: Could not access your certificate: bad key type."); } BouncyCastleCertProcessingFactory factory = BouncyCastleCertProcessingFactory.getDefault(); try { int bits = org.globus.myproxy.MyProxy.DEFAULT_KEYBITS; proxy = factory.createCredential(new X509Certificate[] { (X509Certificate) cert }, (PrivateKey) key, bits, lifetimeHours * 3600, proxyType); } catch (Exception ex) { throw new Exception("Failed to create a proxy:" + ex.getMessage()); } return proxy; }
From source file:com.sshtools.j2ssh.authentication.PKCS12Dialog.java
License:Open Source License
public GlobusCredential showPrompt() throws AuthenticationProtocolException { Security.addProvider(new BouncyCastleProvider()); File keyfile = null;/* w w w.jav a 2 s . c o m*/ String passphrase = null; if (keyfile == null || !keyfile.exists()) { JFileChooser chooser = new JFileChooser(); chooser.setFileHidingEnabled(false); chooser.setDialogTitle("Select Certificate File For Authentication"); if (chooser.showOpenDialog(parent) == JFileChooser.APPROVE_OPTION) { keyfile = chooser.getSelectedFile(); } else { return null; } } Window w = (Window) SwingUtilities.getAncestorOfClass(Window.class, parent); PassphraseDialog dialog = null; if (w instanceof Frame) { dialog = new PassphraseDialog((Frame) w); } else if (w instanceof Dialog) { dialog = new PassphraseDialog((Dialog) w); } else { dialog = new PassphraseDialog(); } KeyStore store = null; do { dialog.setVisible(true); if (dialog.isCancelled()) { return null; } passphrase = new String(dialog.getPassphrase()); try { store = KeyStore.getInstance("PKCS12", "BC"); FileInputStream in = new FileInputStream(keyfile); store.load(in, passphrase.toCharArray()); break; } catch (Exception ihke) { dialog.setMessage("Had a problem: " + ihke); dialog.setMessageForeground(Color.red); } } while (true); try { Enumeration e = store.aliases(); if (!e.hasMoreElements()) return null; String alias = (String) e.nextElement(); java.security.cert.Certificate cert = store.getCertificate(alias); Key key = store.getKey(alias, passphrase.toCharArray()); // System.out.println("Y "+cert[i].getType()+" "+cert[i].getClass().getName()+" "+key.getClass().getName()); if (!(cert instanceof X509Certificate)) return null; if (!(key instanceof PrivateKey)) return null; return new GlobusCredential((PrivateKey) key, new X509Certificate[] { (X509Certificate) cert }); } catch (Exception ihke) { throw new AuthenticationProtocolException("Had a problem: " + ihke); } }
From source file:com.sshtools.j2ssh.authentication.UserGridCredential.java
License:Open Source License
private static GSSCredential retrieveRemoteProxy(SshConnectionProperties properties, int proxyType, int lifetimeHours) throws IOException { GSSCredential gsscredential = null; CoGProperties cogproperties = CoGProperties.getDefault(); String hostname = DEFAULT_MYPROXY_SERVER; hostname = PreferencesStore.get(SshTerminalPanel.PREF_DEFAULT_MYPROXY_HOSTNAME, hostname); String username = System.getProperty("user.name"); username = PreferencesStore.get(SshTerminalPanel.PREF_MYPROXY_UNAME, username); if (properties instanceof SshToolsConnectionProfile) { SshToolsConnectionProfile profile = (SshToolsConnectionProfile) properties; hostname = profile.getApplicationProperty(SshTerminalPanel.PREF_DEFAULT_MYPROXY_HOSTNAME, hostname); username = profile.getApplicationProperty(SshTerminalPanel.PREF_MYPROXY_UNAME, username); }//ww w . j av a 2 s . co m do { boolean flag = false; StringBuffer stringbuffer = new StringBuffer(); StringBuffer stringbuffer1 = new StringBuffer(); StringBuffer stringbuffer2 = new StringBuffer(); if (myProxyPrompt != null) { myProxyPrompt.setHost(hostname); myProxyPrompt.setAccountName(username); boolean flag1 = myProxyPrompt.doGet(properties.getWindow(), stringbuffer, stringbuffer1, stringbuffer2); myProxyPrompt.setError(""); if (flag1) throw new IOException("Canceled by user."); if (myProxyPrompt.getAnother()) return null; StringBuffer stringbufferF = new StringBuffer(); StringBuffer stringbufferP = new StringBuffer(); if (myProxyPrompt.getBrowser()) { gsscredential = chooseCert(proxyType, lifetimeHours, properties); if (gsscredential == null) continue; else return gsscredential; } if (myProxyPrompt.keyBased(stringbufferF, stringbufferP)) { try { KeyStore store = null; String passphrase = stringbufferP.toString(); File keyfile = new File(stringbufferF.toString()); Security.addProvider(new BouncyCastleProvider()); store = KeyStore.getInstance("PKCS12", "BC"); FileInputStream in = new FileInputStream(keyfile); store.load(in, passphrase.toCharArray()); Enumeration e = store.aliases(); if (!e.hasMoreElements()) { JOptionPane.showMessageDialog(properties.getWindow(), "Could not access your certificate: no certificates found in file.", "GSI-SSHTerm Authentication", JOptionPane.ERROR_MESSAGE); continue; } String alias = (String) e.nextElement(); java.security.cert.Certificate cert = store.getCertificate(alias); Key key = store.getKey(alias, passphrase.toCharArray()); if (!(cert instanceof X509Certificate)) { JOptionPane.showMessageDialog(properties.getWindow(), "Could not access your certificate: bad certificate type.", "GSI-SSHTerm Authentication", JOptionPane.ERROR_MESSAGE); continue; } if (!(key instanceof PrivateKey)) { JOptionPane.showMessageDialog(properties.getWindow(), "Could not access your certificate: bad key type.", "GSI-SSHTerm Authentication", JOptionPane.ERROR_MESSAGE); continue; } BouncyCastleCertProcessingFactory factory = BouncyCastleCertProcessingFactory.getDefault(); GlobusCredential globuscredential = factory.createCredential( new X509Certificate[] { (X509Certificate) cert }, (PrivateKey) key, cogproperties.getProxyStrength(), lifetimeHours * 3600, proxyType, (X509ExtensionSet) null); if (globuscredential != null) { if (SAVE_PKCS12_PROXY) { ProxyHelper.saveProxy(globuscredential, properties); } try { globuscredential.verify(); gsscredential = new GlobusGSSCredentialImpl(globuscredential, 1); } catch (Exception exception1) { exception1.printStackTrace(); StringWriter stringwriter1 = new StringWriter(); exception1.printStackTrace(new PrintWriter(stringwriter1)); log.debug(stringwriter1); if (exception1.getMessage().indexOf("Expired credentials") >= 0) { JOptionPane.showMessageDialog(properties.getWindow(), "Your certificate has expired, please renew your certificate or try another method for authentication.", "GSI-SSHTerm Authentication", JOptionPane.ERROR_MESSAGE); continue; } else { errorReport(properties.getWindow(), "Could not load your certificate", exception1); continue; } } } return gsscredential; } catch (java.io.FileNotFoundException exception) { exception.printStackTrace(); StringWriter stringwriter = new StringWriter(); exception.printStackTrace(new PrintWriter(stringwriter)); log.debug(stringwriter); myProxyPrompt.setError("Certificate: could not find file"); continue; } catch (Exception exception) { if (exception.getMessage().indexOf("Illegal key size") >= 0) { exception.printStackTrace(); StringWriter stringwriter = new StringWriter(); exception.printStackTrace(new PrintWriter(stringwriter)); log.debug(stringwriter); errorReport(properties.getWindow(), "To use this PKCS#12 file you need to install the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files\n (see http://java.sun.com/javase/downloads/index.jsp for Java 6 and http://java.sun.com/javase/downloads/index_jdk5.jsp for Java 5)", exception); continue; } else if (exception.getMessage().indexOf("wrong password") >= 0) { exception.printStackTrace(); StringWriter stringwriter = new StringWriter(); exception.printStackTrace(new PrintWriter(stringwriter)); log.debug(stringwriter); myProxyPrompt.setError("Certificate: wrong password?"); continue; } else { exception.printStackTrace(); StringWriter stringwriter = new StringWriter(); exception.printStackTrace(new PrintWriter(stringwriter)); log.debug(stringwriter); errorReport(properties.getWindow(), "Unknown problem while loading your certificate", exception); continue; } } } } CertUtil.init(); // save username if changed: if (!stringbuffer1.toString().equals(username)) { PreferencesStore.put(SshTerminalPanel.PREF_LAST_MYPROXY_USERNAME, stringbuffer1.toString()); } String port_S = DEFAULT_MYPROXY_PORT; port_S = PreferencesStore.get(SshTerminalPanel.PREF_MYPROXY_PORT, port_S); if (properties instanceof SshToolsConnectionProfile) { SshToolsConnectionProfile profile = (SshToolsConnectionProfile) properties; port_S = profile.getApplicationProperty(SshTerminalPanel.PREF_MYPROXY_PORT, port_S); } int port = 7512; try { port = Integer.parseInt(port_S); } catch (NumberFormatException e) { log.warn("Could not parse the port number from defaults file (property name" + SshTerminalPanel.PREF_MYPROXY_PORT + ", property value= " + port_S + ")."); } MyProxy myproxy = null; myproxy = new MyProxy(stringbuffer.toString(), port); try { gsscredential = myproxy.get(null, stringbuffer1.toString(), stringbuffer2.toString(), lifetimeHours * 3600); if (SAVE_MYPROXY_PROXY) { GlobusCredential proxy = ((GlobusGSSCredentialImpl) gsscredential).getGlobusCredential(); ProxyHelper.saveProxy(proxy, properties); } log.debug("A proxy has been received for user " + stringbuffer1); return gsscredential; } catch (Exception exception) { if (exception.getMessage().indexOf("Credentials do not exist") >= 0) { exception.printStackTrace(); StringWriter stringwriter = new StringWriter(); exception.printStackTrace(new PrintWriter(stringwriter)); log.debug(stringwriter); myProxyPrompt.setError("MyProxy: No credentials on server (wrong username?)"); } else if (exception.getMessage().indexOf("Bad password") >= 0) { exception.printStackTrace(); StringWriter stringwriter = new StringWriter(); exception.printStackTrace(new PrintWriter(stringwriter)); log.debug(stringwriter); myProxyPrompt.setError("MyProxy: Bad username and/or password"); } else if (exception.getMessage() .indexOf("Failed to map username too DN via grid-mapfile CA failed to map user") >= 0) { exception.printStackTrace(); StringWriter stringwriter = new StringWriter(); exception.printStackTrace(new PrintWriter(stringwriter)); log.debug(stringwriter); myProxyPrompt.setError("MyProxy: Bad username/password"); } else if (exception.getMessage().indexOf("PAM authentication failed") >= 0) { exception.printStackTrace(); StringWriter stringwriter = new StringWriter(); exception.printStackTrace(new PrintWriter(stringwriter)); log.debug(stringwriter); myProxyPrompt.setError("MyProxy: Bad username/password"); } else if (exception.getMessage().indexOf("credentials have expired") >= 0) { exception.printStackTrace(); StringWriter stringwriter = new StringWriter(); exception.printStackTrace(new PrintWriter(stringwriter)); log.debug(stringwriter); myProxyPrompt.setError("MyProxy: Credentials on server has expired"); } else if (exception.getMessage().indexOf(stringbuffer.toString()) >= 0) { exception.printStackTrace(); StringWriter stringwriter = new StringWriter(); exception.printStackTrace(new PrintWriter(stringwriter)); log.debug(stringwriter); myProxyPrompt.setError("MyProxy: Could not connect to MyProxy server"); } else if (exception.getMessage().indexOf("Password must be at least 6 characters long") >= 0) { exception.printStackTrace(); StringWriter stringwriter = new StringWriter(); exception.printStackTrace(new PrintWriter(stringwriter)); log.debug(stringwriter); myProxyPrompt.setError("MyProxy: Password must be at least 6 characters long."); } else { exception.printStackTrace(); StringWriter stringwriter = new StringWriter(); exception.printStackTrace(new PrintWriter(stringwriter)); log.debug(stringwriter); errorReport(properties.getWindow(), "Unknown problem while accessing MyProxy", exception); continue; } } } while (true); }
From source file:com.streamsets.pipeline.lib.remote.FTPAndSSHDUnitTest.java
License:Apache License
@BeforeClass public static void beforeClass() { Security.addProvider(new BouncyCastleProvider()); }