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:duthientan.mmanm.com.CipherRSA.java

@Override
public void encrypt(String filePath) {
    try {/*from  w w  w.j  a v  a 2 s  .c om*/
        Cipher ecipher = Cipher.getInstance("RSA");
        ecipher.init(Cipher.ENCRYPT_MODE, publicKey);
        Path path = Paths.get(filePath);
        String encryptFilePath = path.getParent().toString() + "/" + "RSA" + "_"
                + path.getFileName().toString();
        byte[] data = Files.readAllBytes(path);
        byte[] textEncrypted = null;
        int chunkSize = 245;
        if (data.length < 245) {
            textEncrypted = ecipher.doFinal(data);
        } else {
            for (int i = 0; i < data.length; i += chunkSize) {
                byte[] segment = Arrays.copyOfRange(data, i,
                        i + chunkSize > data.length ? data.length : i + chunkSize);
                byte[] segmentEncrypted = ecipher.doFinal(segment);
                textEncrypted = ArrayUtils.addAll(textEncrypted, segmentEncrypted);
            }
        }
        FileOutputStream fos = new FileOutputStream(encryptFilePath);
        fos.write(textEncrypted);
        fos.close();
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(CipherRSA.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchPaddingException ex) {
        Logger.getLogger(CipherRSA.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidKeyException ex) {
        Logger.getLogger(CipherRSA.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(CipherRSA.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IllegalBlockSizeException ex) {
        Logger.getLogger(CipherRSA.class.getName()).log(Level.SEVERE, null, ex);
    } catch (BadPaddingException ex) {
        Logger.getLogger(CipherRSA.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.earldouglas.xjdl.io.LicenseLoader.java

protected License decryptLicense(String encodedLicense)
        throws BadPaddingException, UnsupportedEncodingException, Exception {
    byte[] encryptedLicense = Base64.decodeBase64(encodedLicense);

    SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), "AES");
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
    byte[] serializedLicense = cipher.doFinal(encryptedLicense);

    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(serializedLicense);
    ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
    License license = (License) objectInputStream.readObject();
    objectInputStream.close();/*from  w w  w .java2 s  .  c  o m*/
    return license;
}

From source file:hh.learnj.test.license.test.rsacoder.RSACoder.java

/**
 * ?//from  ww w. j a  v a  2  s.  c  o  m
 * 
 * @param data?
 * @param key
 *            
 * @return byte[] ?
 */
public static byte[] encryptByPrivateKey(byte[] data, byte[] key) throws Exception {

    // ??
    PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(key);
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
    // ??
    PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
    // ?
    Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
    cipher.init(Cipher.ENCRYPT_MODE, privateKey);
    return cipher.doFinal(data);
}

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

/**
 * @see corner.encrypt.services.EncryptService#encrypt(byte[], byte[])
 *///from w w  w. j a  v  a2s.  com
@Override
public byte[] encrypt(byte[] src, byte[] key) {
    try {
        SecretKey deskey = new SecretKeySpec(key, Algorithm);
        Cipher c1 = Cipher.getInstance(Algorithm);
        c1.init(Cipher.ENCRYPT_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.elle.analyster.admissions.AESCrypt.java

public static String decrypt(String key, String initVector, String encrypted) {
    try {/*  w w w  .j av a2 s  . c o m*/
        IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
        SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");

        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
        cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);

        byte[] original = cipher.doFinal(Base64.decodeBase64(encrypted));

        return new String(original);
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    return null;
}

From source file:com.github.sshw.crypt.EncryptionBean.java

public String encrypt(String message, String password) throws Exception {
    Cipher encrypt = Cipher.getInstance("AES/CBC/PKCS5Padding");
    Key key = keyFromPassword(password);
    IvParameterSpec ivb = new IvParameterSpec(key.getEncoded());
    encrypt.init(Cipher.ENCRYPT_MODE, key, ivb);
    byte[] cb = encrypt.doFinal(message.getBytes());
    String c = Base64.encodeBase64URLSafeString(cb);
    return c;//from w w  w.j  a v a 2  s.c  o  m
}

From source file:com.feedzai.commons.sql.abstraction.util.AESHelper.java

/**
 * Decrypts a string encrypted by {@link #encrypt} method.
 *
 * @param c   The encrypted HEX string.//  w ww. ja  v  a  2 s . com
 * @param key The  key.
 * @return The decrypted string.
 */
public static String decrypt(String c, String key) {
    try {
        SecretKeySpec skeySpec = new SecretKeySpec(Hex.decodeHex(key.toCharArray()), "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, skeySpec);
        byte[] decoded = cipher.doFinal(Hex.decodeHex(c.toCharArray()));
        return new String(decoded);
    } catch (Exception e) {
        logger.warn("Could not decrypt string", e);
        return null;
    }
}

From source file:cn.org.once.cstack.utils.CustomPasswordEncoder.java

@Override
public String encode(CharSequence sequence) {
    Cipher cipher;/*from  w  ww .  j ava  2  s. c  o  m*/
    String encryptedString = null;
    try {
        cipher = Cipher.getInstance(ALGO);
        cipher.init(Cipher.ENCRYPT_MODE, generateKey());
        encryptedString = Base64.encodeBase64String(cipher.doFinal(sequence.toString().getBytes()));
    } catch (Exception e) {
        e.printStackTrace();
    }
    return encryptedString;
}

From source file:com.credomatic.gprod.db2query2csv.Security.java

/**
 * Cifra una cadena de carateres utilizando el algoritmo AES y una llave (128, 256, o 512 bits). 
 * @param KeySize tamao de la llave autogenerada para relizar el cifrado
 * @param value cadena de caracteres que sera cifrada
 * @return instancia de tipo ${@link SecurityParams} con el resultado del proceso de cifrado
 *//* w w  w .  jav  a  2  s  . c o m*/
public static SecurityParams encrypt(int KeySize, String value) {

    SecurityParams result = null;
    try {
        // Get the KeyGenerator
        final KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(KeySize);

        // Generate the secret key specs.
        final SecretKey skey = kgen.generateKey();
        final byte[] raw = skey.getEncoded();
        final SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        final Cipher cipher = Cipher.getInstance("AES");

        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        final String key = new Base64().encodeAsString(raw);
        final String encrypt = (new Base64()).encodeAsString(cipher.doFinal(value.getBytes()));

        result = new SecurityParams(encrypt, key, KeySize);

    } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException
            | BadPaddingException ex) {
        Logger.getLogger(Security.class.getName()).log(Level.SEVERE, null, ex);
    }
    return result;
}

From source file:com.boulmier.machinelearning.jobexecutor.encrypted.AES.java

public String decrypt(String strToDecrypt) {
    try {/*  w ww  .  jav  a 2  s  .com*/
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");

        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        return (new String(cipher.doFinal(Base64.decodeBase64(strToDecrypt))));

    } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException
            | BadPaddingException e) {

        System.out.println("Error while decrypting: " + e.toString());

    }
    return null;
}