List of usage examples for javax.crypto.spec SecretKeySpec getEncoded
public byte[] getEncoded()
From source file:org.apache.hadoop.security.alias.JavaKeyStoreProvider.java
@Override public CredentialEntry getCredentialEntry(String alias) throws IOException { readLock.lock();//from w w w . ja va 2 s . c o m try { SecretKeySpec key = null; try { if (cache.containsKey(alias)) { return cache.get(alias); } if (!keyStore.containsAlias(alias)) { return null; } key = (SecretKeySpec) keyStore.getKey(alias, password); } catch (KeyStoreException e) { throw new IOException("Can't get credential " + alias + " from " + path, e); } catch (NoSuchAlgorithmException e) { throw new IOException("Can't get algorithm for credential " + alias + " from " + path, e); } catch (UnrecoverableKeyException e) { throw new IOException("Can't recover credential " + alias + " from " + path, e); } return new CredentialEntry(alias, bytesToChars(key.getEncoded())); } finally { readLock.unlock(); } }
From source file:org.apache.taverna.security.credentialmanager.impl.CredentialManagerImpl.java
/** * Get a username and password pair for the given service's URI, or null if * it does not exit.// w ww .j a v a 2s . co m * <p> * If the username and password are not available in the Keystore, it will * invoke implementations of the {@link ServiceUsernameAndPasswordProvider} * interface asking the user (typically through the UI) or resolving * hard-coded credentials. * <p> * If the parameter <code>useURIPathRecursion</code> is true, then the * Credential Manager will also attempt to look for stored credentials for * each of the parent fragments of the URI. * * @param serviceURI * The URI of the service for which we are providing the username * and password * @param useURIPathRecursion * Whether to look for any username and passwords stored in the * Keystore for the parent fragments of the service URI (for * example, we are looking for the credentials for service * http://somehost/some-fragment but we already have credentials * stored for http://somehost which can be reused) * @param requestingMessage * The message to be presented to the user when asking for the * username and password, normally useful for UI providers that * pop up dialogs, can be ignored otherwise * @return username and password pair for the given service * @throws CMException * if anything goes wrong during Keystore lookup, etc. */ @Override public UsernamePassword getUsernameAndPasswordForService(URI serviceURI, boolean usePathRecursion, String requestingMessage) throws CMException { // Need to make sure we are initialized before we do anything else // as Credential Manager can be created but not initialized initialize(); synchronized (keystore) { SecretKeySpec passwordKey = null; LinkedHashSet<URI> possibleServiceURIsToLookup = getPossibleServiceURIsToLookup(serviceURI, usePathRecursion); Map<URI, URI> allServiceURIs = getFragmentMappedURIsForAllUsernameAndPasswordPairs(); try { for (URI lookupURI : possibleServiceURIsToLookup) { URI mappedURI = allServiceURIs.get(lookupURI); if (mappedURI == null) continue; // We found it - get the username and password in the // Keystore associated with this service URI String alias = null; alias = "password#" + mappedURI.toASCIIString(); passwordKey = (((SecretKeySpec) keystore.getKey(alias, masterPassword.toCharArray()))); if (passwordKey == null) { // Unexpected, it was just there in the map! logger.warn("Could not find alias " + alias + " for known uri " + lookupURI + ", just deleted?"); // Remember we went outside synchronized(keystore) while // looping continue; } String unpasspair = new String(passwordKey.getEncoded(), UTF_8); /* * decoded key contains string * <USERNAME><SEPARATOR_CHARACTER><PASSWORD> */ int separatorAt = unpasspair.indexOf(USERNAME_AND_PASSWORD_SEPARATOR_CHARACTER); if (separatorAt < 0) throw new CMException("Invalid credentials stored for " + lookupURI); String username = unpasspair.substring(0, separatorAt); String password = unpasspair.substring(separatorAt + 1); UsernamePassword usernamePassword = new UsernamePassword(); usernamePassword.setUsername(username); usernamePassword.setPassword(password.toCharArray()); return usernamePassword; } // Nothing found in the Keystore, let's lookup using the service // username and password providers for (ServiceUsernameAndPasswordProvider provider : serviceUsernameAndPasswordProviders) { UsernamePassword usernamePassword = provider.getServiceUsernameAndPassword(serviceURI, requestingMessage); if (usernamePassword == null) continue; if (usernamePassword.isShouldSave()) { URI uri = serviceURI; if (usePathRecursion) uri = normalizeServiceURI(serviceURI); addUsernameAndPasswordForService(usernamePassword, uri); } return usernamePassword; } // Giving up return null; } catch (Exception ex) { String exMessage = "Failed to get the username and password pair for service " + serviceURI + " from the Keystore"; logger.error(exMessage, ex); throw new CMException(exMessage, ex); } } }
From source file:org.entrystore.repository.security.Password.java
public static String sha256(String s) { MessageDigest digester;/*from w w w .j a v a2 s . c o m*/ try { digester = MessageDigest.getInstance("SHA-256"); digester.update(s.getBytes("UTF-8")); byte[] key = digester.digest(); SecretKeySpec spec = new SecretKeySpec(key, "AES"); return Base64.encodeBase64String(spec.getEncoded()); } catch (NoSuchAlgorithmException nsae) { log.error(nsae.getMessage()); } catch (UnsupportedEncodingException uee) { log.error(uee.getMessage()); } return null; }
From source file:org.jgrades.security.utils.KeyStoreContentExtractorTest.java
@Test public void shouldExtractPrivateKeyForEncryption() throws Exception { // when//from w w w. j a va 2 s .co m SecretKeySpec secretKeySpec = extractor.getPrivateKeyForEncryptionAndDecryption(); // then assertThat(secretKeySpec).isNotNull(); assertThat(secretKeySpec.getAlgorithm()).isEqualTo("AES"); assertThat(secretKeySpec.getEncoded()).isEqualTo(FileUtils.readFileToByteArray(cryptoPrivateKey)); }
From source file:org.josso.tooling.gshell.install.commands.InstallWebGatewayCommand.java
protected void installConfig() throws Exception { if (copyConfigFiles) { // Generate a key for rememberme auth SecretKeySpec key = CipherUtil.generateAESKey(); byte[] keyBytes = key.getEncoded(); String keyStr = CipherUtil.encodeBase64(keyBytes); FileObject authProperties = tmpDir.resolveFile("josso-auth.properties"); authProperties.createFile();//from ww w.ja v a2 s . c o m OutputStream os = authProperties.getContent().getOutputStream(true); java.util.Properties authProps = new java.util.Properties(); authProps.setProperty("josso.rememberme.authscheme.key", keyStr); authProps.store(os, "JOSSO 'Remember Me' authentication schemem properties."); printer.printActionOkStatus("Generating", "'Remember Me' AES key", "Created " + authProperties.getName().getFriendlyURI()); getInstaller().installConfiguration( createArtifact(tmpDir.getURL().toString(), JOSSOScope.GATEWAY, "josso-auth.properties"), isReplaceConfig()); try { authProperties.delete(); } catch (java.io.IOException e) { /* */ } String persistenceFileName = "josso-gateway-" + persistence + "-stores.xml"; printer.printActionOkStatus("Using", "'" + persistence + "' default configuration", "Installing " + persistenceFileName + " as " + "josso-gateway-stores.xml"); // Install all configuration files : FileObject[] libs = confDir.getChildren(); for (int i = 0; i < confDir.getChildren().length; i++) { FileObject cfgFile = libs[i]; if (!cfgFile.getType().getName().equals(FileType.FILE.getName())) { // ignore folders continue; } String fileName = cfgFile.getName().getBaseName(); if (fileName.equals(persistenceFileName)) { getInstaller().installConfiguration( createArtifact(confDir.getURL().toString(), JOSSOScope.GATEWAY, fileName), "josso-gateway-stores.xml", isReplaceConfig()); } getInstaller().installConfiguration( createArtifact(confDir.getURL().toString(), JOSSOScope.GATEWAY, fileName), isReplaceConfig()); } } else { //TODO backup configuration files, if they exist io.out.println("Backup and remove existing configuration files"); getInstaller().backupGatewayConfigurations(true); } }
From source file:uk.ac.bbsrc.tgac.miso.integration.util.SignatureHelper.java
public static String generatePrivateUserKey(byte[] data) throws NoSuchAlgorithmException { SecretKeySpec signingKey = new SecretKeySpec(data, DSA_ALGORITHM); return Base64.encodeBase64URLSafeString(signingKey.getEncoded()); }