Example usage for javax.crypto.spec SecretKeySpec getEncoded

List of usage examples for javax.crypto.spec SecretKeySpec getEncoded

Introduction

In this page you can find the example usage for javax.crypto.spec SecretKeySpec getEncoded.

Prototype

public byte[] getEncoded() 

Source Link

Document

Returns the key material of this secret key.

Usage

From source file:MainClass.java

public static void main(String[] args) throws Exception {

    SecureRandom random = new SecureRandom();
    byte[] keyBytes = new byte[20];
    random.nextBytes(keyBytes);//  w w  w.  j  a  va 2s  .  c  o m
    SecretKeySpec key = new SecretKeySpec(keyBytes, "HMACSHA1");

    System.out.println("Key:" + new BASE64Encoder().encode(key.getEncoded()));

    Mac mac = Mac.getInstance("HmacSHA1");
    mac.init(key);

    mac.update("test".getBytes("UTF8"));
    byte[] result = mac.doFinal();

    System.out.println("MAC: " + new BASE64Encoder().encode(result));
}

From source file:com.alibaba.openapi.client.util.SignatureUtil.java

public static String getKeyString(SecretKeySpec key) {
    try {//  w  w w .j av a 2s. c  o  m
        return new String(key.getEncoded(), CHARSET_NAME_UTF8);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException("key format error:" + e.getMessage());
    }
}

From source file:uk.ac.tgac.bbsrc.miso.external.ajax.ExternalSectionControllerHelperService.java

public static String generatePrivateUserKey(byte[] data) throws NoSuchAlgorithmException {
    SecretKeySpec signingKey = new SecretKeySpec(data, "DSA");
    return Base64.encodeBase64URLSafeString(signingKey.getEncoded());
}

From source file:be.fedict.eid.idp.protocol.openid.StatelessServerAssociationStore.java

/**
 * Main constructor.//  w w w .j  a va 2  s  . com
 * 
 * @param secretKeySpec
 *            the AES secret key to protect the handle (confidentiality).
 * @param macSecretKeySpec
 *            the MAC secret key to protect the handle (integrity).
 */
public StatelessServerAssociationStore(SecretKeySpec secretKeySpec, SecretKeySpec macSecretKeySpec) {
    int length = secretKeySpec.getEncoded().length;
    if (length != 16 && length != 24 && length != 32) {
        throw new IllegalArgumentException("secret key should be 16/24/32 bytes");
    }
    this.secretKeySpec = secretKeySpec;
    this.macSecretKeySpec = macSecretKeySpec;
    this.secureRandom = new SecureRandom();
    this.secureRandom.setSeed(System.currentTimeMillis());
}

From source file:cl.niclabs.tscrypto.common.messages.EncryptedData.java

private void addData(byte[] blob) {
    SecretKeySpec skeySpec = generateAESKey();
    encryptedData = new String(Base64.encodeBase64(encryptAES(skeySpec, blob)));
    encryptedKey = new String(Base64.encodeBase64(encrypt(skeySpec.getEncoded())));
}

From source file:net.sf.taverna.t2.security.credentialmanager.impl.CredentialManagerImpl.java

/**
 * Get a username and password pair for the given service's URI, or null if
 * it does not exit.//from www. ja v a 2  s  . 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
     * the 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 = "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.apache.hadoop.crypto.key.JavaKeyStoreProvider.java

@Override
public KeyVersion getKeyVersion(String versionName) throws IOException {
    readLock.lock();//w  ww.  j  a v a2  s.  co  m
    try {
        SecretKeySpec key = null;
        try {
            if (!keyStore.containsAlias(versionName)) {
                return null;
            }
            key = (SecretKeySpec) keyStore.getKey(versionName, password);
        } catch (KeyStoreException e) {
            throw new IOException("Can't get key " + versionName + " from " + path, e);
        } catch (NoSuchAlgorithmException e) {
            throw new IOException("Can't get algorithm for key " + key + " from " + path, e);
        } catch (UnrecoverableKeyException e) {
            throw new IOException("Can't recover key " + key + " from " + path, e);
        }
        return new KeyVersion(getBaseName(versionName), versionName, key.getEncoded());
    } finally {
        readLock.unlock();
    }
}

From source file:org.apache.hadoop.crypto.key.RangerKeyStoreProvider.java

@Override
public KeyVersion getKeyVersion(String versionName) throws IOException {
    readLock.lock();//  www  .  j  av a 2 s.co  m
    try {
        SecretKeySpec key = null;
        try {
            if (!dbStore.engineContainsAlias(versionName)) {
                dbStore.engineLoad(null, masterKey);
                if (!dbStore.engineContainsAlias(versionName)) {
                    return null;
                }
            }
            key = (SecretKeySpec) dbStore.engineGetKey(versionName, masterKey);
        } catch (NoSuchAlgorithmException e) {
            throw new IOException("Can't get algorithm for key " + key, e);
        } catch (UnrecoverableKeyException e) {
            throw new IOException("Can't recover key " + key, e);
        } catch (CertificateException e) {
            throw new IOException("Certificate exception storing key", e);
        }
        if (key == null) {
            return null;
        } else {
            return new KeyVersion(getBaseName(versionName), versionName, key.getEncoded());
        }
    } finally {
        readLock.unlock();
    }
}

From source file:org.apache.hadoop.mapreduce.security.TestTokenCache.java

private static void createTokenFileJson() throws IOException {
    Map<String, String> map = new HashMap<String, String>();

    try {//from w w  w  . jav a 2  s.co m
        KeyGenerator kg = KeyGenerator.getInstance("HmacSHA1");
        for (int i = 0; i < NUM_OF_KEYS; i++) {
            SecretKeySpec key = (SecretKeySpec) kg.generateKey();
            byte[] enc_key = key.getEncoded();
            map.put("alias" + i, new String(Base64.encodeBase64(enc_key)));

        }
    } catch (NoSuchAlgorithmException e) {
        throw new IOException(e);
    }

    try {
        File p = new File(tokenFileName.getParent().toString());
        p.mkdirs();
        // convert to JSON and save to the file
        mapper.writeValue(new File(tokenFileName.toString()), map);

    } catch (Exception e) {
        System.out.println("failed with :" + e.getLocalizedMessage());
    }
}

From source file:org.apache.hadoop.security.alias.AbstractJavaKeyStoreProvider.java

@Override
public CredentialEntry getCredentialEntry(String alias) throws IOException {
    readLock.lock();/*w ww  .  j  a  v a  2 s .  c  om*/
    try {
        SecretKeySpec key = null;
        try {
            if (!keyStore.containsAlias(alias)) {
                return null;
            }
            key = (SecretKeySpec) keyStore.getKey(alias, password);
        } catch (KeyStoreException e) {
            throw new IOException("Can't get credential " + alias + " from " + getPathAsString(), e);
        } catch (NoSuchAlgorithmException e) {
            throw new IOException("Can't get algorithm for credential " + alias + " from " + getPathAsString(),
                    e);
        } catch (UnrecoverableKeyException e) {
            throw new IOException("Can't recover credential " + alias + " from " + getPathAsString(), e);
        }
        return new CredentialEntry(alias, bytesToChars(key.getEncoded()));
    } finally {
        readLock.unlock();
    }
}