Example usage for javax.crypto Cipher ENCRYPT_MODE

List of usage examples for javax.crypto Cipher ENCRYPT_MODE

Introduction

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

Prototype

int ENCRYPT_MODE

To view the source code for javax.crypto Cipher ENCRYPT_MODE.

Click Source Link

Document

Constant used to initialize cipher to encryption mode.

Usage

From source file:com.zotoh.core.crypto.JavaOfuscator.java

private String encrypt(String clearText) throws Exception {
    if (isEmpty(clearText)) {
        return clearText;
    }/*from w  w  w  .java 2  s .co  m*/
    Cipher c = getCipher(Cipher.ENCRYPT_MODE);
    ByteOStream baos = new ByteOStream();
    byte[] p = asBytes(clearText);
    byte[] out = new byte[Math.max(4096, c.getOutputSize(p.length))];
    int n = c.update(p, 0, p.length, out, 0);
    if (n > 0) {
        baos.write(out, 0, n);
    }
    n = c.doFinal(out, 0);
    if (n > 0) {
        baos.write(out, 0, n);
    }

    return Base64.encodeBase64URLSafeString(baos.asBytes());
}

From source file:ch.newscron.encryption.Encryption.java

/**
 * Given a JSONObject, and maybe an hash, it is encoded and returned as a String.
 * @param inviteData is a JSONObject having the data with the keys "customerId", "rew1", "rew2" and "val"
 * @param md5Hash is a String that substitute the hash computed using md5 algorithm, in case it is not null and not empty
 * @return encoded string /*from   w ww .j  ava2s  .  co  m*/
 */
protected static String encode(JSONObject inviteData, String md5Hash) {

    try {
        //Check in case we want to add a given hash (having at the end a corrupt data)
        if (md5Hash != null && !md5Hash.isEmpty()) {
            //Add md5Hash to JSONObject
            inviteData.put("hash", md5Hash);
        } else {
            return null;
        }

        //Encode inviteData (with hash) JSONObject
        String params = inviteData.toString();
        final SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey,
                new IvParameterSpec(initializationVector.getBytes("UTF-8")));
        return Base64.encodeBase64URLSafeString(cipher.doFinal(params.getBytes())); //to ensure valid URL characters
    } catch (Exception e) {
    }

    return null;
}

From source file:com.aerohive.nms.engine.admin.task.licensemgr.common.AerohiveEncryptTool.java

public AerohiveEncryptTool(String arg_Key) {
    if (arg_Key != null && !arg_Key.trim().equals(""))
        m_Str_Key = arg_Key;

    try {/* w w  w.  j a v  a 2 s  .c om*/
        // Create the key
        KeySpec keySpec = new PBEKeySpec(m_Str_Key.toCharArray(), m_Byte_Salt, m_Int_IterationCount);
        SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
        m_Cipher_Ecipher = Cipher.getInstance(key.getAlgorithm());
        m_Cipher_Dcipher = Cipher.getInstance(key.getAlgorithm());

        // Prepare the parameter to the ciphers
        AlgorithmParameterSpec paramSpec = new PBEParameterSpec(m_Byte_Salt, m_Int_IterationCount);

        // Create the ciphers
        m_Cipher_Ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
        m_Cipher_Dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
    } catch (Exception e) {
        //DebugUtil.commonDebugWarn(e.getMessage());
    }
}

From source file:com.ec2box.manage.util.EncryptionUtil.java

/**
 * return encrypted value of string/*from   w  w  w  .j a v  a2  s. c o  m*/
 *
 * @param str unencrypted string
 * @return encrypted string
 */
public static String encrypt(String str) {

    String retVal = null;
    if (str != null && str.length() > 0) {
        try {
            Cipher c = Cipher.getInstance("AES");
            c.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"));
            byte[] encVal = c.doFinal(str.getBytes());
            retVal = new String(Base64.encodeBase64(encVal));
        } catch (Exception ex) {
            log.error(ex.toString(), ex);
        }

    }
    return retVal;
}

From source file:com.haulmont.timesheets.EncryptDecrypt.java

public EncryptDecrypt(String key) {
    try {//from w ww.j  a  va  2  s .c  om
        String data = new StringBuilder(SALT + key).reverse().toString();
        SecretKeySpec secretKey = new SecretKeySpec(DigestUtils.md5(data), "AES");
        AlgorithmParameterSpec paramSpec = new IvParameterSpec(INIT_VECTOR);
        eCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        dCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        eCipher.init(Cipher.ENCRYPT_MODE, secretKey, paramSpec);
        dCipher.init(Cipher.DECRYPT_MODE, secretKey, paramSpec);
    } catch (Exception e) {
        throw new RuntimeException("Exception while init cipher:", e);
    }
}

From source file:com.parleys.server.frontend.web.ipad.filters.AESEncrypter.java

private AESEncrypter(final Key key) {
    try {//from w  ww .  j a  v  a 2s. co m
        ecipher = Cipher.getInstance("AES");
        dcipher = Cipher.getInstance("AES");
        ecipher.init(Cipher.ENCRYPT_MODE, key);
        dcipher.init(Cipher.DECRYPT_MODE, key);
    } catch (Exception e) {
        LOGGER.fatal(e);
        throw new RuntimeException("Error generating key");
    }
}

From source file:com.cloud.utils.crypt.RSAHelper.java

public static String encryptWithSSHPublicKey(String sshPublicKey, String content) {
    String returnString = null;//from www. j a  v a 2 s .co  m
    try {
        RSAPublicKey publicKey = readKey(sshPublicKey);
        Cipher cipher = Cipher.getInstance("RSA/None/PKCS1Padding", BouncyCastleProvider.PROVIDER_NAME);
        cipher.init(Cipher.ENCRYPT_MODE, publicKey, new SecureRandom());
        byte[] encrypted = cipher.doFinal(content.getBytes());
        returnString = Base64.encodeBase64String(encrypted);
    } catch (Exception e) {
    }

    return returnString;
}

From source file:com.dasol.util.AES256Util.java

public String aesEncode(String str) throws java.io.UnsupportedEncodingException, NoSuchAlgorithmException,
        NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException,
        IllegalBlockSizeException, BadPaddingException {
    Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
    c.init(Cipher.ENCRYPT_MODE, keySpec, new IvParameterSpec(iv.getBytes()));

    byte[] encrypted = c.doFinal(str.getBytes("UTF-8"));
    String enStr = new String(Base64.encodeBase64(encrypted));

    return enStr;
}

From source file:com.rr.familyPlanning.ui.security.encryptObject.java

/**
 * Encrypts and encodes the Object and IV for url inclusion
 *
 * @param input/*from ww w.j  a  v a2s  .  c  om*/
 * @return
 * @throws Exception
 */
public String[] encryptObject(Object obj) throws Exception {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    ObjectOutput out = new ObjectOutputStream(stream);
    try {
        // Serialize the object
        out.writeObject(obj);
        byte[] serialized = stream.toByteArray();
        // Setup the cipher and Init Vector
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        byte[] iv = new byte[cipher.getBlockSize()];
        new SecureRandom().nextBytes(iv);
        IvParameterSpec ivSpec = new IvParameterSpec(iv);
        // Hash the key with SHA-256 and trim the output to 128-bit for the key
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        digest.update(keyString.getBytes());
        byte[] key = new byte[16];
        System.arraycopy(digest.digest(), 0, key, 0, key.length);
        SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
        // encrypt
        cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
        // Encrypt & Encode the input
        byte[] encrypted = cipher.doFinal(serialized);
        byte[] base64Encoded = Base64.encodeBase64(encrypted);
        String base64String = new String(base64Encoded);
        String urlEncodedData = URLEncoder.encode(base64String, "UTF-8");
        // Encode the Init Vector
        byte[] base64IV = Base64.encodeBase64(iv);
        String base64IVString = new String(base64IV);
        String urlEncodedIV = URLEncoder.encode(base64IVString, "UTF-8");

        return new String[] { urlEncodedData, urlEncodedIV };
    } finally {
        stream.close();
        out.close();
    }
}

From source file:com.cloudant.sync.datastore.encryption.DPKEncryptionUtil.java

/**
 * AES Encrypt a byte array/*from www  .j  a v a  2  s.  c  o m*/
 *
 * @param key              The encryption key
 * @param iv               The iv
 * @param unencryptedBytes The data to encrypt
 * @return The encrypted data
 * @throws NoSuchPaddingException
 * @throws NoSuchAlgorithmException
 * @throws InvalidAlgorithmParameterException
 * @throws InvalidKeyException
 * @throws BadPaddingException
 * @throws IllegalBlockSizeException
 */
public static byte[] encryptAES(SecretKey key, byte[] iv, byte[] unencryptedBytes)
        throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException,
        InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
    Cipher aesCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    IvParameterSpec ivParameter = new IvParameterSpec(iv);
    // see http://stackoverflow.com/a/11506343
    Key encryptionKey = new SecretKeySpec(key.getEncoded(), "AES");
    aesCipher.init(Cipher.ENCRYPT_MODE, encryptionKey, ivParameter);
    return aesCipher.doFinal(unencryptedBytes);
}