Example usage for javax.crypto Cipher DECRYPT_MODE

List of usage examples for javax.crypto Cipher DECRYPT_MODE

Introduction

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

Prototype

int DECRYPT_MODE

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

Click Source Link

Document

Constant used to initialize cipher to decryption mode.

Usage

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

public static String Decrypt(String str) {
    // create cryptography object
    SecretKeyFactory keyFactory;//from   ww w . ja  v a2  s  . c om
    try {
        keyFactory = 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 = keyFactory.generateSecret(new PBEKeySpec(PASSWORD));
    } catch (InvalidKeySpecException e) {
        return "";
    }

    // init cipher
    Cipher pbeCipher;
    try {
        pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
    } catch (NoSuchAlgorithmException e) {
        return "";
    } catch (NoSuchPaddingException e) {
        return "";
    }

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

    // decode & return decoded string
    String dec;

    try {
        dec = new String(pbeCipher.doFinal(base64Decode(str)));
    } catch (IllegalBlockSizeException e) {
        return "";
    } catch (BadPaddingException e) {
        return "";
    } catch (IOException e) {
        return "";
    }

    return dec;
}

From source file:Crypto.ChiffreDES.java

@Override
public String decrypt(String cipherText) //passer des bytes
{
    String TextClairDecrypte = null;
    try {/*  w w  w.j  a  v  a  2 s.  co m*/
        Cipher chiffrementD = Cipher.getInstance("DES/ECB/PKCS5Padding", "BC");
        chiffrementD.init(Cipher.DECRYPT_MODE, Cle.getSecretKey());
        byte[] DecodedBytes = cipherText.getBytes();
        byte[] DecodedBytes64 = Base64.decodeBase64(DecodedBytes);
        byte[] textDecode = chiffrementD.doFinal(DecodedBytes64);
        TextClairDecrypte = new String(textDecode);
        System.out.println("Test Dcrypt = " + TextClairDecrypte);
    } 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 (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 (InvalidKeyException ex) {
        Logger.getLogger(ChiffreDES.class.getName()).log(Level.SEVERE, null, ex);
    }
    return TextClairDecrypte;
}

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

@Test
public void symetric() throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException,
        InvalidKeyException, IllegalBlockSizeException, BadPaddingException {

    KeyGenerator kg = KeyGenerator.getInstance("AES");
    kg.init(256, new SecureRandom());
    Key k = kg.generateKey();//  w  ww. j a v  a2s . c o m

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

    c.init(Cipher.ENCRYPT_MODE, k);
    c.update(plainBytes);

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

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

    assertEquals(plain, dec);
}

From source file:com.confighub.core.security.Encryption.java

private static String decryptShared(CipherTransformation ct, String encrypted, String secret)
        throws ConfigException {
    if (null == encrypted)
        return null;

    try {/* w  ww.j  ava 2 s .  c  om*/
        Cipher cipher = Cipher.getInstance(ct.getName());
        final int blockSize = cipher.getBlockSize();

        SecretKeySpec sharedKey = new SecretKeySpec(getKeyAsBytes(secret, ct.getKeyLen()), ct.getAlgo());

        if ("CBC".equals(ct.getMode()))
            cipher.init(Cipher.DECRYPT_MODE, sharedKey, new IvParameterSpec(getIV(blockSize)));
        else
            cipher.init(Cipher.DECRYPT_MODE, sharedKey);

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

        return new String(decrypted, "UTF8");
    } catch (Exception e) {
        throw new ConfigException(Error.Code.DECRYPTION_ERROR);
    }
}

From source file:com.aurel.track.report.query.ReportQueryBL.java

private static String dcl(String encryptedText, char[] password) {
    byte[] clearText = { ' ' };
    int count = 20;
    PBEKeySpec pbeKeySpec;/* w  w  w  . j a  va 2 s  .c  o m*/
    PBEParameterSpec pbeParamSpec;
    SecretKeyFactory keyFac;
    // Create PBE parameter set
    pbeParamSpec = new PBEParameterSpec(salt, count);
    pbeKeySpec = new PBEKeySpec(password);
    try {
        keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);

        // Create PBE Cipher
        Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");

        // Initialize PBE Cipher with key and parameters
        pbeCipher.init(Cipher.DECRYPT_MODE, pbeKey, pbeParamSpec);

        byte[] ciphertext = Base64.decodeBase64(encryptedText);

        // Decrypt the cleartext
        clearText = pbeCipher.doFinal(ciphertext);
    } catch (Exception e) {
    }
    return new String(clearText);
}

From source file:com.frame.Conf.Utilidades.java

/**
 * /*w  w w  . ja  v a2s . c om*/
 * @param keypass Es la llave plublica para desencriptar el texto
 * @param textoEncriptado hash del texto a desencriptar
 * @return retorna el texto desencriptado
 * @throws Exception 
 */
public String Desencriptar(String keypass, String textoEncriptado) throws Exception {

    String secretKey = keypass; //llave para encriptar datos
    String base64EncryptedString = "";

    try {
        System.out.println("checkpoint");
        byte[] message = Base64.decodeBase64(textoEncriptado.getBytes("utf-8"));
        MessageDigest md = MessageDigest.getInstance("MD5");
        System.out.println("checkpoint2");
        byte[] digestOfPassword = md.digest(secretKey.getBytes("utf-8"));
        byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
        System.out.println("checkpoint3");
        SecretKey key = new SecretKeySpec(keyBytes, "DESede");

        System.out.println("checkpoint4");
        Cipher decipher = Cipher.getInstance("DESede");
        decipher.init(Cipher.DECRYPT_MODE, key);
        System.out.println("checkpoint5");

        byte[] plainText = decipher.doFinal(message);
        System.out.println("checkpoint6");
        base64EncryptedString = new String(plainText, "UTF-8");

    } catch (UnsupportedEncodingException | NoSuchAlgorithmException | NoSuchPaddingException
            | InvalidKeyException | IllegalBlockSizeException | BadPaddingException ex) {
        throw new Exception(ex.getMessage());
    }
    return base64EncryptedString;
}

From source file:com.xwiki.authentication.AbstractAuthServiceImpl.java

protected String decryptText(String text, XWikiContext context) {
    try {/*from  w w w.j av a 2  s. c  o  m*/
        String secretKey = null;
        secretKey = context.getWiki().Param("xwiki.authentication.encryptionKey");
        secretKey = secretKey.substring(0, 24);

        if (secretKey != null) {
            SecretKeySpec key = new SecretKeySpec(secretKey.getBytes(), "TripleDES");
            Cipher cipher = Cipher.getInstance("TripleDES");
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] encrypted = Base64.decodeBase64(text.replaceAll("_", "=").getBytes("ISO-8859-1"));
            String decoded = new String(cipher.doFinal(encrypted));
            return decoded;
        } else {
            LOG.error("Encryption key not defined");
        }
    } catch (Exception e) {
        LOG.error("Failed to decrypt text", e);
    }

    return null;
}

From source file:at.tfr.securefs.util.Main.java

public void parseOpts(String[] args) throws Exception {

    List<String> argList = Arrays.asList(args);
    Iterator<String> iter = argList.iterator();

    if (args.length == 0) {
        System.out.println("Usage: [options] <file>");
        System.out.println("<file>: file to use for de/encryption");
        System.out.println("Options:");
        System.out.println("\t-t\tTest using test key with file");
        System.out.println("\t-d\tdecrypt file with test key - default");
        System.out.println("\t-e\tencrypt file with test key");
        System.out.println("\t-s <salt> \tsalt - default: use file name");
        System.out.println("\t-b <path> \base path for file access, default use ClassLoader roots");
        System.out.println("\t-o <outFile> \tfile to write to, relative to basePath");
        System.exit(0);/*from  w  ww  .j a  v a2 s  . c o m*/
    }

    while (iter.hasNext()) {
        String a = iter.next();

        switch (a) {
        case "-t":
            test = true;
            break;
        case "-d":
            mode = Cipher.DECRYPT_MODE;
            break;
        case "-e":
            mode = Cipher.ENCRYPT_MODE;
            break;
        case "-s":
            configuration.setSalt(iter.next());
            break;
        case "-b":
            basePath = new File(iter.next()).toPath();
            break;
        case "-o":
            outFile = iter.next();
            break;
        default:
            file = a;
        }
    }

    if (file == null)
        throw new FileNotFoundException("no file defined");

    if (basePath == null) {
        URL resource = this.getClass().getResource("/" + file);
        if (resource == null)
            throw new FileNotFoundException("cannot find basePath for file: " + file);
        URI uri = resource.toURI();
        String absolutePath = new File(uri).getAbsolutePath();
        basePath = new File(absolutePath).getParentFile().toPath();
    }

}

From source file:com.thoughtworks.go.server.util.EncryptionHelper.java

public static String decryptUsingAES(SecretKey secretKey, String dataToDecrypt) throws NoSuchPaddingException,
        NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
    Cipher aesCipher = Cipher.getInstance("AES");
    aesCipher.init(Cipher.DECRYPT_MODE, secretKey);
    byte[] bytePlainText = aesCipher.doFinal(Base64.getDecoder().decode(dataToDecrypt));
    return new String(bytePlainText);
}

From source file:com.aurel.track.admin.customize.category.filter.execute.ReportQueryBL.java

private static String dcl(String encryptedText, char[] password) {
    byte[] clearText = { ' ' };
    int count = 20;
    PBEKeySpec pbeKeySpec;/*  ww  w . j a va2s.c  o  m*/
    PBEParameterSpec pbeParamSpec;
    SecretKeyFactory keyFac;
    // Create PBE parameter set
    pbeParamSpec = new PBEParameterSpec(salt, count);
    pbeKeySpec = new PBEKeySpec(password);
    try {
        keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);

        // Create PBE Cipher
        Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");

        // Initialize PBE Cipher with key and parameters
        pbeCipher.init(Cipher.DECRYPT_MODE, pbeKey, pbeParamSpec);

        byte[] ciphertext = Base64.decodeBase64(encryptedText);

        //Decrypt the cleartext
        clearText = pbeCipher.doFinal(ciphertext);
    } catch (Exception e) {
        LOGGER.debug(ExceptionUtils.getStackTrace(e), e);
    }
    return new String(clearText);
}