password Decrypt - Android java.security

Android examples for java.security:Password

Description

password Decrypt

Demo Code


//package com.java2s;

import java.io.ByteArrayInputStream;

import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;

public class Main {
    private static final int ITERATIONS = 1000;

    public static byte[] passwordDecrypt(char[] password, byte[] ciphertext) {
        byte[] salt = new byte[8];
        ByteArrayInputStream bais = new ByteArrayInputStream(ciphertext);
        bais.read(salt, 0, 8);//from   www  .  j a  v a 2  s .  c om

        byte[] remainingCiphertext = new byte[ciphertext.length - 8];
        bais.read(remainingCiphertext, 0, ciphertext.length - 8);

        PBEKeySpec keySpec = new PBEKeySpec(password);
        SecretKeyFactory keyFactory = null;
        try {
            keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        SecretKey secretKey = null;
        try {
            secretKey = keyFactory.generateSecret(keySpec);
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        }

        PBEParameterSpec paramSpec = new PBEParameterSpec(salt, ITERATIONS);

        Cipher cipher = null;
        try {
            cipher = Cipher.getInstance("PBEWithMD5AndDES");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        }
        try {
            cipher.init(Cipher.DECRYPT_MODE, secretKey, paramSpec);
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
        }

        try {
            return cipher.doFinal(remainingCiphertext);
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return null;
    }
}

Related Tutorials