Example usage for javax.crypto Cipher getInstance

List of usage examples for javax.crypto Cipher getInstance

Introduction

In this page you can find the example usage for javax.crypto Cipher getInstance.

Prototype

public static final Cipher getInstance(String transformation)
        throws NoSuchAlgorithmException, NoSuchPaddingException 

Source Link

Document

Returns a Cipher object that implements the specified transformation.

Usage

From source file:jatoo.properties.FileProperties.java

public FileProperties(File file, Key key) throws GeneralSecurityException {

    this.file = file;

    cipherEncrypt = Cipher.getInstance("AES/ECB/PKCS5Padding");
    cipherEncrypt.init(Cipher.ENCRYPT_MODE, key);

    cipherDecrypt = Cipher.getInstance("AES/ECB/PKCS5Padding");
    cipherDecrypt.init(Cipher.DECRYPT_MODE, key);
}

From source file:com.ro.ssc.app.client.licensing.TrialKeyGenerator.java

public static String generateKey(String toEncode) {

    String encoded = "";
    try {/* w  w w  .  j  a  v a2  s  . c o m*/
        byte[] saltEncrypt = SALT_ENCRYPT.getBytes();
        SecretKeyFactory factoryKeyEncrypt = SecretKeyFactory.getInstance(SECRET_KEY_FACTORY);
        SecretKey tmp = factoryKeyEncrypt.generateSecret(
                new PBEKeySpec(PASS_ENCRYPT.toCharArray(), saltEncrypt, ITERATIONS_ENCRYPT, KEY_LENGTH));
        SecretKeySpec encryptKey = new SecretKeySpec(tmp.getEncoded(), ALGORITHM);
        Cipher aesCipherEncrypt = Cipher.getInstance(CIPHER);
        aesCipherEncrypt.init(Cipher.ENCRYPT_MODE, encryptKey);
        byte[] bytes = StringUtils.getBytesUtf8(toEncode);
        byte[] encryptBytes = aesCipherEncrypt.doFinal(bytes);
        encoded = Base64.encodeBase64URLSafeString(encryptBytes);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return encoded;
}

From source file:com.enviosya.client.tool.Tool.java

public String Desencriptar(String textoEncriptado) throws Exception {

    //String secretKey = "qualityinfosolutions"; //llave para desenciptar datos
    String base64EncryptedString = "";

    try {//from  w ww. j av a2 s .  c o m
        byte[] message = Base64.decodeBase64(textoEncriptado.getBytes("utf-8"));
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] digestOfPassword = md.digest(secretKey.getBytes("utf-8"));
        byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
        SecretKey key = new SecretKeySpec(keyBytes, "DESede");

        Cipher decipher = Cipher.getInstance("DESede");
        decipher.init(Cipher.DECRYPT_MODE, key);

        byte[] plainText = decipher.doFinal(message);

        base64EncryptedString = new String(plainText, "UTF-8");

    } catch (Exception e) {
        //Ac tengo que agregar el retorno de la exception
    }
    return base64EncryptedString;
}

From source file:com.example.license.RSAUtil.java

/**
 * ?//  w w  w . j  ava  2  s  . c  o  m
 * 
 * @param data
 *            ?
 * @param key
 *            
 * @return ??
 */
public static String decrypt(String data, String seed) throws Exception {
    KeyPair keyPair = generatorKeyPair(seed);
    Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
    // ?Cipher?
    cipher.init(Cipher.DECRYPT_MODE, keyPair.getPublic());
    // ?
    return new String(cipher.doFinal(Base64.decodeBase64(data)));
}

From source file:com.cloud.consoleproxy.ConsoleProxyPasswordBasedEncryptor.java

public String encryptText(String text) {
    if (text == null || text.isEmpty())
        return text;

    assert (password != null);
    assert (!password.isEmpty());

    try {//w ww  .j ava  2s  .  c o m
        Cipher cipher = Cipher.getInstance("DES");
        int maxKeySize = 8;
        SecretKeySpec keySpec = new SecretKeySpec(normalizeKey(password.getBytes(), maxKeySize), "DES");
        cipher.init(Cipher.ENCRYPT_MODE, keySpec);
        byte[] encryptedBytes = cipher.doFinal(text.getBytes());
        return Base64.encodeBase64URLSafeString(encryptedBytes);
    } catch (NoSuchAlgorithmException e) {
        s_logger.error("Unexpected exception ", e);
        return null;
    } catch (NoSuchPaddingException e) {
        s_logger.error("Unexpected exception ", e);
        return null;
    } catch (IllegalBlockSizeException e) {
        s_logger.error("Unexpected exception ", e);
        return null;
    } catch (BadPaddingException e) {
        s_logger.error("Unexpected exception ", e);
        return null;
    } catch (InvalidKeyException e) {
        s_logger.error("Unexpected exception ", e);
        return null;
    }
}

From source file:com.arvato.thoroughly.util.security.impl.AES128AttributeEncryptionStrategy.java

public String decrypt(final String c) throws Exception {
    if (StringUtils.isNotEmpty(c)) {
        final Cipher cipher = Cipher.getInstance(ENCRYPTION_ALGORITHM);
        final SecretKeySpec keySpec = getKeySpec();

        cipher.init(2, keySpec);/*from   w ww . j a v a 2  s  . co  m*/

        final byte[] decoded = new Hex().decode(c.getBytes());
        final byte[] decrypted = cipher.doFinal(decoded);
        return new String(decrypted);
    }
    return c;
}

From source file:com.cisco.ca.cstg.pdi.services.license.LicenseCryptoServiceImpl.java

public void encryptToFile() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
        IllegalBlockSizeException, BadPaddingException, IOException {
    BufferedWriter out = null;//from w  ww.j a v  a 2s .c o  m
    try {
        byte[] raw = getPassword().getBytes(Charset.forName(Constants.UTF8));
        SecretKeySpec skeySpec = new SecretKeySpec(raw, ALGORITHM_BLOWFISH);
        Cipher cipher = null;
        cipher = Cipher.getInstance(ALGORITHM_BLOWFISH);
        cipher.init(1, skeySpec);
        byte[] output = cipher.doFinal(getMetaData().getBytes());
        BigInteger n = new BigInteger(output);

        String b64hidden = Base64.encodeBase64String(n.toString(16).getBytes());
        setAssessmentKey(b64hidden);

        out = new BufferedWriter(new FileWriter(this.getAssessmentKeyFileName()));
        out.write(b64hidden);
    } finally {
        if (out != null) {
            out.close();
        }
    }
}

From source file:com.tremolosecurity.unison.u2f.util.U2fUtil.java

public static String encode(List<SecurityKeyData> devices, String encyrptionKeyName) throws Exception {
    ArrayList<KeyHolder> keys = new ArrayList<KeyHolder>();
    for (SecurityKeyData dr : devices) {
        KeyHolder kh = new KeyHolder();
        kh.setCounter(dr.getCounter());// w  w  w  . j a v a 2  s.  c o  m
        kh.setEnrollmentTime(dr.getEnrollmentTime());
        kh.setKeyHandle(dr.getKeyHandle());
        kh.setPublicKey(dr.getPublicKey());
        kh.setTransports(dr.getTransports());
        keys.add(kh);
    }

    String json = gson.toJson(keys);
    EncryptedMessage msg = new EncryptedMessage();

    SecretKey key = GlobalEntries.getGlobalEntries().getConfigManager().getSecretKey(encyrptionKeyName);
    if (key == null) {
        throw new Exception("Queue message encryption key not found");
    }

    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, key);
    msg.setMsg(cipher.doFinal(json.getBytes("UTF-8")));
    msg.setIv(cipher.getIV());

    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    DeflaterOutputStream compressor = new DeflaterOutputStream(baos,
            new Deflater(Deflater.BEST_COMPRESSION, true));

    compressor.write(gson.toJson(msg).getBytes("UTF-8"));
    compressor.flush();
    compressor.close();

    String b64 = new String(Base64.encodeBase64(baos.toByteArray()));

    return b64;

}

From source file:it.geosolutions.figis.persistence.dao.util.PwEncoder.java

/**
 * Decode the password on base 64/*from  www . ja  v  a  2s  .  c  om*/
 * @param msg
 * @return
 */
public static String decode(String msg) {
    try {
        SecretKeySpec keySpec = new SecretKeySpec(KEY, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, keySpec);

        byte[] de64 = Base64.decodeBase64(msg);
        byte[] decrypted = cipher.doFinal(de64);

        return new String(decrypted);
    } catch (NoSuchAlgorithmException ex) {
        throw new RuntimeException("Error while encoding", ex);
    } catch (NoSuchPaddingException ex) {
        throw new RuntimeException("Error while encoding", ex);
    } catch (IllegalBlockSizeException ex) {
        throw new RuntimeException("Error while encoding", ex);
    } catch (BadPaddingException ex) {
        throw new RuntimeException("Error while encoding", ex);
    } catch (InvalidKeyException ex) {
        throw new RuntimeException("Error while encoding", ex);
    }
}

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

/**
 *
 *
 * @param mode/*from ww w .  ja v  a  2 s. com*/
 * @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");
    }
}