Example usage for javax.crypto.spec SecretKeySpec SecretKeySpec

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

Introduction

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

Prototype

public SecretKeySpec(byte[] key, String algorithm) 

Source Link

Document

Constructs a secret key from the given byte array.

Usage

From source file:corner.services.impl.DESedeEncryptServiceImpl.java

public byte[] decrypt(byte[] src, byte[] keybyte) {
    try {/*from  w ww. j  av a  2  s  .  c o  m*/
        SecretKey deskey = new SecretKeySpec(keybyte, Algorithm);
        Cipher c1 = Cipher.getInstance(Algorithm);
        c1.init(Cipher.DECRYPT_MODE, deskey);
        return c1.doFinal(src);
    } catch (java.security.NoSuchAlgorithmException e1) {
        e1.printStackTrace();
    } catch (javax.crypto.NoSuchPaddingException e2) {
        e2.printStackTrace();
    } catch (java.lang.Exception e3) {
        e3.printStackTrace();
    }
    return null;
}

From source file:com.bytecode.util.Crypto.java

private static Key generateKey(String keystring, int bits) throws Exception {
    byte[] keyBytes = new byte[bits];
    byte[] key = new byte[bits];
    for (int i = 0; i < bits; i++) {
        keyBytes[i] = (byte) keystring.codePointAt(i);
    }/*from  ww  w.jav a2s.c o  m*/
    SecretKey secretKey = new SecretKeySpec(keyBytes, "AES");
    Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
    cipher.init(Cipher.ENCRYPT_MODE, secretKey);
    key = cipher.doFinal(keyBytes);
    for (int i = 0; i < bits - 16; i++) {
        key[16 + i] = key[i];
    }

    return new SecretKeySpec(key, "AES");
}

From source file:com.lling.qiqu.utils.AesUtils.java

/**
 * Encrypts a message using a 128bit Bse64 key using AES.
 *
 * @param key     128bit Base64 AES key/*w ww . j  a  v  a  2s.  c o m*/
 * @param message Message to encrypt
 * @return hex encoded encrypted message
 */
public static String encrypt(String key, String message) {
    String encrypted = "";
    try {
        // Generate the secret key specs.
        byte[] keyArray = Base64.decodeBase64(key.getBytes());
        SecretKeySpec skeySpec = new SecretKeySpec(keyArray, "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypt = cipher.doFinal(message.getBytes());
        encrypted = new String(hexCodec.encode(encrypt));
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        throw new RuntimeException(e);
    }
    return encrypted;
}

From source file:gsn.http.ac.Protector.java

private static Key generateKey() throws Exception {
    Key key = new SecretKeySpec(keyValue, ALGORITHM);
    return key;//from w  ww.j  ava 2s  .  c  o  m
}

From source file:com.kolich.aws.signing.impl.KolichAwsSigner.java

@Override
public final String sign(final AwsCredentials credentials, final String input) {
    try {//  w  w  w . j  av  a 2s  .  co m
        final String algoName = algorithm_.toString();
        // Get a new instance of the HMAC-SHA1 algorithm.
        final Mac mac = Mac.getInstance(algoName);
        // Init it with our secret and the secret-key algorithm.
        mac.init(new SecretKeySpec(credentials.getSecretBytes(), algoName));
        // Sign the input.
        return encodeBase64ToString(mac.doFinal(getBytesUtf8(input)));
    } catch (Exception e) {
        throw new KolichAwsException(
                "Failed to sign input " + "string (algorithm=" + algorithm_ + ", input=" + input + ")", e);
    }
}

From source file:net.thewaffleshop.nimbus.api.EncryptionAPI.java

/**
 * Generate a {@link SecretKey} from a password and salt
 *
 * @param password/* w w  w  .  j  a v a  2  s.  co m*/
 * @param salt
 * @return
 */
public SecretKey createSecretKey(String password, byte[] salt) {
    try {
        PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt, 1024, 256);
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        SecretKey secretKey = factory.generateSecret(keySpec);
        return new SecretKeySpec(secretKey.getEncoded(), "AES");
    } catch (GeneralSecurityException e) {
        throw new RuntimeException(e);
    }
}

From source file:algorithm.AesEncryption.java

private void setKey(String function) {

    MessageDigest sha = null;//w  w  w.jav  a 2  s . co m
    try {
        //File f = new File("Aes_key");
        key = new byte[16];
        //   KeyGenerator kgen = KeyGenerator.getInstance("AES");

        //TODO : SET 128/196/256 keysize
        //generise kljuc od 128
        //         kgen.init(128);
        //NE KORISTI SE!!!
        //      secretKey = kgen.generateKey();
        //TODO : Set md5/SHA / SHA-1/ SHA-256
        //   sha = MessageDigest.getInstance("SHA-256");
        sha = MessageDigest.getInstance(function);
        key = sha.digest(key);

        // use only first 128 bit
        key = Arrays.copyOf(key, 16);

        secretKeySpec = new SecretKeySpec(key, "AES");

        //  new FileOutputStream(f).write(key);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
}

From source file:com.sshtools.j2ssh.transport.cipher.BlowfishCbc.java

/**
 *
 *
 * @param mode/*  w w w. j  av a  2  s. c  om*/
 * @param iv
 * @param keydata
 *
 * @throws AlgorithmOperationException
 */
public void init(int mode, byte[] iv, byte[] keydata) throws AlgorithmOperationException {
    try {
        cipher = Cipher.getInstance("Blowfish/CBC/NoPadding");

        // Create a 16 byte key
        byte[] actualKey = new byte[16];
        System.arraycopy(keydata, 0, actualKey, 0, actualKey.length);

        SecretKeySpec keyspec = new SecretKeySpec(actualKey, "Blowfish");

        // Create the cipher according to its algorithm
        cipher.init(((mode == ENCRYPT_MODE) ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE), keyspec,
                new IvParameterSpec(iv, 0, cipher.getBlockSize()));
    } catch (NoSuchPaddingException nspe) {
        log.error("Blowfish initialization failed", nspe);
        throw new AlgorithmOperationException("No Padding not supported");
    } catch (NoSuchAlgorithmException nsae) {
        log.error("Blowfish initialization failed", nsae);
        throw new AlgorithmOperationException("Algorithm not supported");
    } catch (InvalidKeyException ike) {
        log.error("Blowfish initialization failed", ike);
        throw new AlgorithmOperationException("Invalid encryption key");

        /*} catch (InvalidKeySpecException ispe) {
             throw new AlgorithmOperationException("Invalid encryption key specification");*/
    } catch (InvalidAlgorithmParameterException ape) {
        log.error("Blowfish initialization failed", ape);
        throw new AlgorithmOperationException("Invalid algorithm parameter");
    }
}

From source file:com.antonjohansson.elasticsearchshell.client.PasswordEncrypter.java

/**
 * Decrypts the given password, using the username as salt.
 *
 * @param username The username, used for salt.
 * @param password The password to decrypt.
 * @return The decrypted password./*from  ww w .  ja  v  a  2 s .co m*/
 */
String decrypt(String username, String password) {
    try {
        String key = rightPad(username, KEY_SIZE).substring(0, KEY_SIZE);
        Key spec = new SecretKeySpec(key.getBytes(), algorithm);
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(DECRYPT_MODE, spec);
        byte[] decrypted = cipher.doFinal(Base64.getDecoder().decode(password));
        return new String(decrypted);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:edu.wfu.inotado.helper.EncryptionHelper.java

public String calculateHMAC(String data, String key) throws java.security.SignatureException {
    String result = "";
    try {//from   w  ww. j  a  v  a2 s . c  o  m

        if (!StringUtils.isBlank(data) && !StringUtils.isBlank(key)) {
            // get an hmac_sha1 key from the raw key bytes
            SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM);

            // get an hmac_sha1 Mac instance and initialize with the signing key
            Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
            mac.init(signingKey);

            // compute the hmac on input data bytes
            byte[] rawHmac = mac.doFinal(data.getBytes());

            // base64-encode the hmac
            result = new String(Base64.encodeBase64(rawHmac));
        } else {
            log.warn("data or key appears to be empty!");
        }
    } catch (Exception e) {
        throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
    }
    return result;
}