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.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());//from  www  .  ja  va  2  s.  co  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:com.demandware.vulnapp.challenge.impl.ECBOracleChallenge.java

protected ECBOracleChallenge(String name) {
    super(name);/*from w w w .  j a  v  a  2 s  . co  m*/
    this.keyType = "AES";
    this.encryptionType = "AES/ECB/NoPadding";
    try {
        SecretKey key = generateKey();
        this.eCipher = Cipher.getInstance(this.encryptionType);
        this.eCipher.init(Cipher.ENCRYPT_MODE, key);
        this.dCipher = Cipher.getInstance(this.encryptionType);
        this.dCipher.init(Cipher.DECRYPT_MODE, key);
    } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException e) {
        throw new SetupRuntimeException(e);
    }
    tryRoundtrip();
}

From source file:net.bioclipse.encryption.Encrypter.java

public String encrypt(String plaintext) {
    SecretKeyFactory keyFac;//from w w w.j  a v a 2 s.co m
    SecretKey pbeKey;
    Cipher pbeCipher;
    try {
        keyFac = SecretKeyFactory.getInstance(METHOD);
        pbeKey = keyFac.generateSecret(pbeKeySpec);
        pbeCipher = Cipher.getInstance(METHOD);
        pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);
        return new String(Base64.encodeBase64(pbeCipher.doFinal(plaintext.getBytes())));
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException(e);
    } catch (InvalidKeySpecException e) {
        throw new IllegalStateException(e);
    } catch (NoSuchPaddingException e) {
        throw new IllegalStateException(e);
    } catch (InvalidKeyException e) {
        throw new IllegalStateException(e);
    } catch (InvalidAlgorithmParameterException e) {
        throw new IllegalStateException(e);
    } catch (IllegalBlockSizeException e) {
        throw new IllegalStateException(e);
    } catch (BadPaddingException e) {
        throw new IllegalStateException(e);
    }
}

From source file:net.sf.jftp.config.Crypto.java

public static String Encrypt(String str) {
    // create cryptography object
    SecretKeyFactory factory;/*from   w w w.  jav  a2s .c o m*/
    try {
        factory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
    } catch (NoSuchAlgorithmException e) {
        // We could try another algorithm, but it is highly unlikely that this would be the case
        return "";
    }

    // init key
    SecretKey key;

    try {
        key = factory.generateSecret(new PBEKeySpec(PASSWORD));
    } catch (InvalidKeySpecException e) {
        // The password is hard coded - this exception can't be the case
        return "";
    }

    // init cipher
    Cipher pbeCipher;
    try {
        pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
    } catch (NoSuchPaddingException e) {
        // We could try another algorithm, but it is highly unlikely that this would be the case
        return "";
    } catch (NoSuchAlgorithmException e) {
        // We could try another algorithm, but it is highly unlikely that this would be the case
        return "";
    }

    try {
        pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(SALT, 20));
    } catch (InvalidKeyException e) {
        return "";
    } catch (InvalidAlgorithmParameterException e) {
        return "";
    }

    // encode & return encoded string
    try {
        return base64Encode(pbeCipher.doFinal(str.getBytes()));
    } catch (IllegalBlockSizeException e) {
        return "";
    } catch (BadPaddingException e) {
        return "";
    }
}

From source file:com.intel.chimera.codec.JceAesCtrCryptoCodec.java

@Override
public Encryptor createEncryptor() throws GeneralSecurityException {
    return new JceAesCtrCipher(Cipher.ENCRYPT_MODE, provider);
}

From source file:Crypto.ChiffreDES.java

@Override
public String crypte(String plainTextObj) // passer un String et return des bytes
{
    Security.addProvider(new BouncyCastleProvider());
    String plainText = (String) plainTextObj;
    String textCr = null;/* w ww.  j av a2  s .  co m*/
    byte[] texteCrypte = null;
    byte[] encodedBytes = null;
    try {
        Cipher chiffrement = Cipher.getInstance("DES/ECB/PKCS5Padding", "BC");
        chiffrement.init(Cipher.ENCRYPT_MODE, this.Cle.getSecretKey());
        byte[] texteClair = plainText.getBytes();
        byte[] ciphertext = chiffrement.doFinal(texteClair);
        encodedBytes = Base64.encodeBase64(ciphertext);
        System.out.println("EncodedBytes" + new String(encodedBytes));
    } catch (IllegalBlockSizeException ex) {
        Logger.getLogger(ChiffreDES.class.getName()).log(Level.SEVERE, null, ex);
    } catch (BadPaddingException ex) {
        Logger.getLogger(ChiffreDES.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(ChiffreDES.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchProviderException ex) {
        Logger.getLogger(ChiffreDES.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchPaddingException ex) {
        Logger.getLogger(ChiffreDES.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidKeyException ex) {
        Logger.getLogger(ChiffreDES.class.getName()).log(Level.SEVERE, null, ex);
    }

    return new String(encodedBytes);
}

From source file:corner.util.crypto.Cryptor.java

/**
 * IO?,IO??,./*from   ww w .j  ava2 s  .c om*/
 * @param outFileName ??. 
 * @param keyFile ??.
 * @return ??.
 */
public static OutputStream encryptFileIO(String outFileName, String keyFile) {
    if (keyFile == null) {
        try {
            return new FileOutputStream(outFileName);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
    SecretKey key = null;

    //?
    ObjectInputStream keyis;
    try {
        keyis = new ObjectInputStream(new FileInputStream(keyFile));
        key = (SecretKey) keyis.readObject();
        keyis.close();
    } catch (FileNotFoundException e) {
        log.error("file not found!", e);
        throw new RuntimeException("file not found", e);
    } catch (IOException e) {
        log.error("io occour exception", e);
        throw new RuntimeException(e);
    } catch (ClassNotFoundException e) {
        log.error("Class Not Found  exception", e);
        throw new RuntimeException(e);
    }

    //keyCipher
    Cipher cipher = null;
    //?Cipher?

    try {
        cipher = Cipher.getInstance("DES");
        //?

        cipher.init(Cipher.ENCRYPT_MODE, key);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    } catch (NoSuchPaddingException e) {
        throw new RuntimeException(e);
    } catch (InvalidKeyException e) {
        throw new RuntimeException(e);
    }

    //???

    //
    CipherOutputStream out = null;
    try {
        out = new CipherOutputStream(new BufferedOutputStream(new FileOutputStream(outFileName)), cipher);
    } catch (FileNotFoundException e) {
        throw new RuntimeException(e);
    }

    return out;

}

From source file:club.jmint.crossing.specs.Security.java

public static String desEncrypt(String data, String key) throws CrossException {
    String ret = null;/* ww  w  .j  a  v  a  2s .com*/
    try {
        DESKeySpec desKey = new DESKeySpec(key.getBytes("UTF-8"));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey securekey = keyFactory.generateSecret(desKey);

        Cipher cipher = Cipher.getInstance(CIPHER_DES_ALGORITHM);
        SecureRandom random = new SecureRandom();
        cipher.init(Cipher.ENCRYPT_MODE, securekey, random);
        byte[] results = cipher.doFinal(data.getBytes("UTF-8"));
        ret = Base64.encodeBase64String(results);
    } catch (Exception e) {
        CrossLog.printStackTrace(e);
        throw new CrossException(ErrorCode.COMMON_ERR_ENCRYPTION.getCode(),
                ErrorCode.COMMON_ERR_ENCRYPTION.getInfo());
    }
    return ret;
}

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 {//  ww w .ja va2 s  .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:uploadProcess.java

public static boolean encrypt(File inputFolder, File outputFolder, String fileName, String patientID) {
    try {/* ww w  .j a v  a2s  .  co  m*/

        String ukey = GetKey.getPatientKey(patientID);
        File filePath = new File(inputFolder.getAbsolutePath() + File.separator + fileName);
        FileInputStream fis = new FileInputStream(filePath);
        File outputFile = new File(outputFolder.getAbsolutePath() + File.separator + fileName);
        FileOutputStream fos = new FileOutputStream(outputFile);
        byte[] k = ukey.getBytes();
        SecretKeySpec key = new SecretKeySpec(k, "AES");
        //            System.out.println(key);
        Cipher enc = Cipher.getInstance("AES");
        enc.init(Cipher.ENCRYPT_MODE, key);
        CipherOutputStream cos = new CipherOutputStream(fos, enc);
        byte[] buf = new byte[1024];
        int read;
        while ((read = fis.read(buf)) != -1) {
            cos.write(buf, 0, read);
        }
        fis.close();
        fos.flush();
        cos.close();

        //Upload File to cloud
        DropboxUpload upload = new DropboxUpload();
        upload.uploadFile(outputFolder, fileName, StoragePath.getDropboxDir() + patientID);
        DeleteDirectory.delete(outputFolder);
        return true;
    } catch (Exception e) {
        System.out.println("Error: " + e);
    }
    return false;
}