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.baidu.rigel.biplatform.ac.util.AesUtil.java

/**
 * ??//  w w  w  .j  av  a 2s  .c  o  m
 * 
 * @param data 
 * @param keyValue 
 * @return ?
 * @throws IllegalArgumentException 
 * @throws Exception InvalidKeyExceptionIllegalBlockSizeException, BadPaddingException?
 */
public String encrypt(String data, String keyValue) throws Exception {
    if (StringUtils.isBlank(data)) {
        throw new IllegalArgumentException("encode string can not be blank!");
    }
    Key key = generateKey(keyValue);
    Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
    ;
    cipher.init(Cipher.ENCRYPT_MODE, key);
    byte[] encVal = cipher.doFinal(data.getBytes());
    String encryptedValue = Base64.getEncoder().encodeToString(encVal);
    return encryptedValue;
}

From source file:org.runway.utils.StringEncryptDecryptUtil.java

public static String encrypt(String property) throws RunwaySecurityException {
    String result = null;//  w w  w.j a v  a  2 s. c  o  m
    SecretKeyFactory keyFactory;
    try {
        keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
        SecretKey key = keyFactory.generateSecret(new PBEKeySpec(PASSWORD));
        Cipher pbeCipher = Cipher.getInstance(ALGORITHM);
        pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(SALT, 20));
        result = base64Encode(pbeCipher.doFinal(property.getBytes()));
    } catch (NoSuchAlgorithmException e) {
        throw new RunwaySecurityException(e);
    } catch (InvalidKeySpecException e) {
        throw new RunwaySecurityException(e);
    } catch (NoSuchPaddingException e) {
        throw new RunwaySecurityException(e);
    } catch (InvalidKeyException e) {
        throw new RunwaySecurityException(e);
    } catch (InvalidAlgorithmParameterException e) {
        throw new RunwaySecurityException(e);
    } catch (IllegalBlockSizeException e) {
        throw new RunwaySecurityException(e);
    } catch (BadPaddingException e) {
        throw new RunwaySecurityException(e);
    }

    return result;
}

From source file:org.matrix.security.crypto.encrypt.AesBytesEncryptor.java

public byte[] encrypt(byte[] bytes) {
    synchronized (encryptor) {
        byte[] iv = ivGenerator.generateKey();
        initCipher(encryptor, Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(iv));
        byte[] encrypted = doFinal(encryptor, bytes);
        return ivGenerator != NULL_IV_GENERATOR ? concatenate(iv, encrypted) : encrypted;
    }/*  w  w w.  ja v  a  2 s .c  o m*/
}

From source file:enc_mods.aes.java

public String getEncryptedString(String str) {
    String encrypted = "";
    if (secretkey == null) {
        System.out.println("no key");
    } else {/*from  w  w  w. j  a v a  2  s. c  om*/
        try {
            cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
            cipher.init(Cipher.ENCRYPT_MODE, secretkey);
            encrypted = Base64.encodeBase64String(cipher.doFinal(str.getBytes("UTF-8")));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return encrypted;
}

From source file:com.bluepixel.security.manager.Server.java

private void generateKey() {
    try {/*from w w w .j  ava2  s. c  om*/
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance(DEFAULT_ALGORITHM);
        keyGen.initialize(DEFAULT_KEY_LENGTH);
        KeyPair keypair = keyGen.generateKeyPair();
        PublicKey pbKey = keypair.getPublic();
        PrivateKey piKey = keypair.getPrivate();

        publicKey = Base64.encodeWebSafe(pbKey.getEncoded(), false);
        privateKey = Base64.encodeWebSafe(piKey.getEncoded(), false);

        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");

        cipher.init(Cipher.ENCRYPT_MODE, piKey);

        secretKeys = new ConcurrentHashMap<String, String>();
        String[] randomKeys = generateRandomWords(10);
        for (String key : randomKeys) {
            String cipherText = Base64.encodeWebSafe(cipher.doFinal(key.getBytes()), false);
            secretKeys.put(key, cipherText);
        }
    } catch (NoSuchAlgorithmException e) {
    } catch (InvalidKeyException e) {
    } catch (NoSuchPaddingException e) {
    } catch (IllegalBlockSizeException e) {
    } catch (BadPaddingException e) {
    }
}

From source file:info.fcrp.keepitsafe.bean.CryptBeanTest.java

@Test
public void assymetric() throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException,
        InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    kpg.initialize(1024, new SecureRandom());
    KeyPair kp = kpg.generateKeyPair();
    PrivateKey priKey = kp.getPrivate();
    PublicKey pubKey = kp.getPublic();

    Cipher c = Cipher.getInstance("RSA");
    String plain = "plain";
    byte[] plainBytes = plain.getBytes();

    c.init(Cipher.ENCRYPT_MODE, pubKey);
    c.update(plainBytes);// w  ww  . ja  va 2  s  .co  m

    byte[] encBytes = c.doFinal();
    String enc = Base64.encodeBase64String(encBytes);
    assertNotSame(plain, enc);

    c.init(Cipher.DECRYPT_MODE, priKey);
    c.update(encBytes);
    byte[] decBytes = c.doFinal();
    String dec = new String(decBytes);

    assertEquals(plain, dec);
}

From source file:com.baran.crypto.CryptoDES.java

public byte[] encrypt(File file, String trivia) throws Exception {
    final MessageDigest md = MessageDigest.getInstance("md5");
    // digest the trivia password in UTF-8
    final byte[] digestTrivia = md.digest(trivia.getBytes("utf-8"));

    // truncating digest
    final byte[] keyBytes = Arrays.copyOf(digestTrivia, 24);
    for (int j = 0, k = 16; j < 8;) {
        keyBytes[k++] = keyBytes[j++];/*w w w .  j ava 2s  .c o m*/
    }
    // DESede setting
    final SecretKey key = new SecretKeySpec(keyBytes, "DESede");

    // CBC IV setting
    final IvParameterSpec iv = new IvParameterSpec(new byte[8]);

    final Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, key, iv);

    String allInOne = FileUtils.readFileToString(file, "utf-8");

    final byte[] plainTextBytes = allInOne.getBytes("utf-8");
    final byte[] cipherText = cipher.doFinal(plainTextBytes);

    return cipherText;
}

From source file:io.stallion.utils.Encrypter.java

public static String encryptString(String password, String value) {
    String salt = KeyGenerators.string().generateKey();
    SecretKeySpec skeySpec = makeKeySpec(password, salt);
    byte[] iv = KeyGenerators.secureRandom(16).generateKey();
    String ivString = Hex.encodeHexString(iv);

    try {//from   w  w w . ja  va2  s  .  co m
        Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new GCMParameterSpec(128, iv));
        /*
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec,
        new IvParameterSpec(iv));
        */

        byte[] encrypted = cipher.doFinal(value.getBytes(Charset.forName("UTF-8")));
        String s = StringUtils.strip(new Base32().encodeAsString(encrypted), "=").toLowerCase();
        // Strip line breaks
        s = salt + ivString + s.replaceAll("(\\n|\\r)", "");
        return s;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:net.networksaremadeofstring.cyllell.Authentication.java

private String SignHeaders(String dataToSign)
        throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException,
        IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException, NoSuchProviderException {
    PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(Base64.decode(this.PrivateKey.getBytes(), 0));
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PrivateKey pk = kf.generatePrivate(spec);
    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1PADDING");
    cipher.init(Cipher.ENCRYPT_MODE, pk);

    byte[] EncryptedStream = new byte[cipher.getOutputSize(dataToSign.length())];
    try {/*from ww w  .  ja  va 2  s.  c o m*/
        cipher.doFinal(dataToSign.getBytes(), 0, dataToSign.length(), EncryptedStream, 0);
    } catch (ShortBufferException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return Base64.encodeToString(EncryptedStream, Base64.NO_WRAP);
}

From source file:algorithm.AesEncryption.java

@Override
public void encryptFile(File clearFile, File encrypted) {

    try {//from   w w  w  .j a v  a2 s  . c  om

        encrypt.init(Cipher.ENCRYPT_MODE, secretKeySpec);

        encryptedString = Base64.encodeBase64String(encrypt.doFinal(buildString(clearFile).getBytes("UTF-8")));

        writeBytes(new ByteArrayInputStream(encryptedString.getBytes(StandardCharsets.UTF_8)),
                new FileOutputStream(encrypted));
    } catch (InvalidKeyException | IllegalBlockSizeException | BadPaddingException | IOException ex) {
        Logger.getLogger(AesEncryption.class.getName()).log(Level.SEVERE, null, ex);
    }

}