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:enc_mods.aes.java

/**
 * Encrypts the AES key to a file using an RSA public key
 *//* w w  w . j a v a2 s. c o m*/
public void saveKey(File out, File publicKeyFile) {
    try {
        // read public key to be used to encrypt the AES key
        byte[] encodedKey = new byte[(int) publicKeyFile.length()];
        new FileInputStream(publicKeyFile).read(encodedKey);

        // create public key
        X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(encodedKey);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        PublicKey pk = kf.generatePublic(publicKeySpec);

        // write AES key
        cipher.init(Cipher.ENCRYPT_MODE, pk);
        CipherOutputStream os = new CipherOutputStream(new FileOutputStream(out), cipher);
        os.write(key);
        os.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:edu.hku.sdb.udf.util.UDFHandler.java

private static boolean search(byte[] encrypted, String keyword, SecretKey prkey) {
    byte[] keywordbyte = keyword.getBytes();
    if (keywordbyte.length != encrypted.length) {
        return false;
    }//from ww  w.  j a  v a2  s .  c om
    byte[] diff1 = new byte[keywordbyte.length - 1];
    for (int i = 0; i < diff1.length; i++) {
        diff1[i] = (byte) (encrypted[i] ^ keywordbyte[i]);
    }
    byte diff2 = (byte) (encrypted[diff1.length] ^ keywordbyte[diff1.length]);
    // get diff = word xor encrypted
    // if it is a match, first part of diff generates second part of diff using pseudo random function

    try {
        // pseudorandom cipher
        Cipher prCipher = Cipher.getInstance(SCHEME);
        prCipher.init(Cipher.ENCRYPT_MODE, prkey);

        // si is chopped with the desired length

        byte[] fksi = prCipher.doFinal(diff1);
        // fksi is F_k(S_i) in the searchable encryption
        // we use the same AES cipher for simplicity

        return fksi[0] == diff2;
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchPaddingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (BadPaddingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return false;
}

From source file:cloudeventbus.pki.CertificateUtils.java

public static byte[] signChallenge(PrivateKey key, byte[] challenge, byte[] salt) {
    try {/*from   w  w w  .j  a  v  a  2s .c  om*/
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        cipher.update(challenge);
        cipher.update(salt);
        return cipher.doFinal();
    } catch (GeneralSecurityException e) {
        throw new CertificateSecurityException(e);
    }
}

From source file:com.servoy.j2db.util.SecuritySupport.java

@SuppressWarnings("nls")
public static String encryptUrlSafe(Settings settings, String value) throws Exception {
    if (value == null)
        return value;
    Cipher cipher = Cipher.getInstance("DESede");
    cipher.init(Cipher.ENCRYPT_MODE, SecuritySupport.getCryptKey(settings));
    return Base64.encodeBase64URLSafeString(cipher.doFinal(value.getBytes()));
}

From source file:net.sourceforge.jencrypt.FileEncrypter.java

/**
 * Shorten the "En-/decrypting [fileOrFolder]" message to 80 chars.
 * /*from   w  w  w  . j  av a 2  s .  c  om*/
 * @param fileOrFolder
 * @param cipherMode
 * @return shortened message
 */
private String getCipherMessage(String fileOrFolder, int cipherMode) {
    // Shorten encryption message to 80 characters
    if (fileOrFolder.length() > 55)
        fileOrFolder = "..." + fileOrFolder.substring(fileOrFolder.length() - 55, fileOrFolder.length());

    return ((cipherMode == Cipher.ENCRYPT_MODE) ? "Encrypting" : "Decrypting") + ": '" + fileOrFolder + "' ";
}

From source file:com.elkriefy.android.apps.authenticationexample.credentialsgrace.CredGraceActivity.java

/**
 * Tries to encrypt some data with the generated key in {@link #createKey} which is
 * only works if the user has just authenticated via device credentials.
 *///from  w w  w .  j a  v  a 2  s.  co  m
private boolean tryEncrypt() {
    try {
        KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
        keyStore.load(null);
        SecretKey secretKey = (SecretKey) keyStore.getKey(KEY_NAME, null);
        Cipher cipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC
                + "/" + KeyProperties.ENCRYPTION_PADDING_PKCS7);

        // Try encrypting something, it will only work if the user authenticated within
        // the last AUTHENTICATION_DURATION_SECONDS seconds.
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        cipher.doFinal(SECRET_BYTE_ARRAY);

        // If the user has recently authenticated, you will reach here.
        showAlreadyAuthenticated();
        return true;
    } catch (UserNotAuthenticatedException e) {
        // User is not authenticated, let's authenticate with device credentials.
        showAuthenticationScreen();
        return false;
    } catch (KeyPermanentlyInvalidatedException e) {
        // This happens if the lock screen has been disabled or reset after the key was
        // generated after the key was generated.
        Toast.makeText(this, "Keys are invalidated after created. Retry the purchase\n" + e.getMessage(),
                Toast.LENGTH_LONG).show();
        return false;
    } catch (BadPaddingException | IllegalBlockSizeException | KeyStoreException | CertificateException
            | UnrecoverableKeyException | IOException | NoSuchPaddingException | NoSuchAlgorithmException
            | InvalidKeyException e) {
        throw new RuntimeException(e);
    }
}

From source file:de.pawlidi.openaletheia.utils.CipherUtils.java

/**
 * // ww  w  .  j  ava  2s. co  m
 * @param data
 * @param key
 * @return
 */
public static byte[] encrypt(byte[] data, Key key) {
    if (key != null && ArrayUtils.isNotEmpty(data)) {
        try {
            Cipher rsaCipher = Cipher.getInstance(CIPHER_EXTENDED_ALGORITHM);
            rsaCipher.init(Cipher.ENCRYPT_MODE, key);
            return rsaCipher.doFinal(data);
        } catch (Exception e) {
            throw new RuntimeException("Cannot encrypt, " + CIPHER_ALGORITHM + " error", e);
        }
    }
    return null;
}

From source file:com.aqnote.shared.cryptology.symmetric.Blowfish.java

/**
 * ?CipherdoFinal?reset ???// ww w . j a  va2 s.com
 * 
 * @param b ?
 * @return ?
 * @throws IllegalBlockSizeException
 * @throws BadPaddingException
 */
public synchronized byte[] encrypt(byte[] b) throws IllegalBlockSizeException, BadPaddingException {
    byte[] buffer = null;
    initCipher(encryptCipher, Cipher.ENCRYPT_MODE, keySpec, paramSpec);
    buffer = encryptCipher.doFinal(b);
    return buffer;
}

From source file:com.hhi.bigdata.platform.push.client.RegisterUtil.java

/**
 * <pre>//from w w  w.  ja  v  a 2s  .  c  o  m
 * private key ? app name? ? ? return
 * </pre>
 * @return
 * @throws Exception
 */
private static String getAppNameEnc(PrivateKey privKey, String appName) throws Exception {
    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.ENCRYPT_MODE, privKey);

    return Base64.encodeBase64String(cipher.doFinal(appName.getBytes()));
}

From source file:com.cyberninjas.xerobillableexpenses.util.Settings.java

private String encryptText(String plainText) {
    try {/*w  w w  .j  a  v  a  2s  . c o m*/
        this.iv = prefs.getByteArray("DRUGS", null);
        if (this.iv == null) { //If not set, set the IV
            cipher.init(Cipher.ENCRYPT_MODE, this.secret);
            AlgorithmParameters params = cipher.getParameters();
            this.iv = params.getParameterSpec(IvParameterSpec.class).getIV();
            prefs.putByteArray("DRUGS", this.iv);
        } else {
            cipher.init(Cipher.ENCRYPT_MODE, this.secret, new IvParameterSpec(this.iv));
        }

        byte[] ciphertext = cipher.doFinal(plainText.getBytes("UTF-8"));
        String ret = new String(Base64.encodeBase64(ciphertext));
        return ret;
    } catch (InvalidParameterSpecException | IllegalBlockSizeException | BadPaddingException
            | UnsupportedEncodingException | InvalidKeyException ex) {
        Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidAlgorithmParameterException ex) {
        Logger.getLogger(Settings.class.getName()).log(Level.SEVERE, null, ex);
    }
    return "";
}