android加密工具类1

1.AES加密

package cn.cw.common.utils;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;


/**
 * ClassName: AESUtils. <br/>
 * Description: AES加密工具类. <br/>
 * Date: 2019年04月10日. <br/>
 *
 * @author
 * @version 2.0.1
 * @since 1.7
 */
public class AESUtils {

    /**
     * -默认字符集
     */
    private static final String CHARSET = "utf-8";

    /**
     * -加密算法
     */
    private static final String KEY_ALGORITHM = "AES";

    /**
     * -填充方式
     */
    private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";

    /**
     * -AES 加密操作
     *
     * @param content
     * @param password
     * @return
     * @throws Exception
     */
    public static String encrypt(String content, String password) {
        Cipher cipher = null;
        byte[] result = null;
        try {
            cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(password));
            byte[] byteContent = content.getBytes(CHARSET);
            result = new byte[0];
            result = cipher.doFinal(byteContent);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }

        return HexUtils.bytesToHex(result);
    }

    /**
     * 加密并base64编码
     *
     * @param content
     * @param password
     * @return
     * @throws Exception
     */
    public static String encryptBase64(String content, String password) throws Exception {
        Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(password));

        byte[] byteContent = content.getBytes(CHARSET);
        byte[] result = cipher.doFinal(byteContent);

        return Base64Utils.encode(result);
    }

    /**
     * -AES 解密操作
     *
     * @param content
     * @param password
     * @return
     * @throws Exception
     */
    public static String decrypt(String content, String password) throws Exception {

        Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, getSecretKey(password));
        byte[] result = cipher.doFinal(HexUtils.hexStringToByte(content));

        return new String(result, CHARSET);
    }

    /**
     * 解密base64字符串
     *
     * @param content
     * @param password
     * @return
     * @throws Exception
     */
    public static String decryptBase64(String content, String password) throws Exception {

        Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, getSecretKey(password));
        byte[] result = cipher.doFinal(Base64Utils.decode(content));

        return new String(result, CHARSET);
    }

    /**
     * -生成加密秘钥
     *
     * @return
     */
    private static SecretKeySpec getSecretKey(final String password) {
        try {
            return new SecretKeySpec(password.getBytes(CHARSET), KEY_ALGORITHM);
        } catch (Exception e) {
            throw new IllegalArgumentException("encode init error");
        }
    }
}

2.DES加密

package cn.cw.common.utils;

import java.io.IOException;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
/**
 * ClassName: DESUtils. <br/>
 * Description: DES加密工具类. <br/>
 * Date:2019年5月20日. <br/>
 *
 * @author 
 * @version 1.1.0
 * @since 1.7
 */
public class DESUtils {
    
    /**
     *-加密算法
     */
    private final static String DES = "DES";
    
    /**
     *-默认字符集
     */
    private final static String CHARSET = "utf-8";

    /**
     *-根据键值进行加密
     * @param data
     * @param key  加密键byte数组
     * @return
     * @throws Exception
     */
    public static String encrypt(String data, String key) throws Exception {
        return Base64Utils.encode(
                encrypt(data.getBytes(CHARSET), key.getBytes(CHARSET)));
    }

    /**
     *-根据键值进行解密
     * @param data
     * @param key  加密键byte数组
     * @return
     * @throws IOException
     * @throws Exception
     */
    public static String decrypt(String data, String key) throws Exception {
        return new String(decrypt(Base64Utils.decode(data), key.getBytes(CHARSET)));
    }

    /**
     *-根据键值进行加密
     * @param data
     * @param key  加密键byte数组
     * @return
     * @throws Exception
     */
    public static byte[] encrypt(byte[] data, byte[] key) throws Exception {
        // 生成一个可信任的随机数源
        SecureRandom sr = new SecureRandom();
    
        // 从原始密钥数据创建DESKeySpec对象
        DESKeySpec dks = new DESKeySpec(key);
    
        // 创建一个密钥工厂,然后用它把DESKeySpec转换成SecretKey对象
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
        SecretKey securekey = keyFactory.generateSecret(dks);
    
        // Cipher对象实际完成加密操作
        Cipher cipher = Cipher.getInstance(DES);
    
        // 用密钥初始化Cipher对象
        cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);
    
        return cipher.doFinal(data);
    }


    /**
     *-根据键值进行解密
     * @param data
     * @param key  加密键byte数组
     * @return
     * @throws Exception
     */
    private static byte[] decrypt(byte[] data, byte[] key) throws Exception {
        // 生成一个可信任的随机数源
        SecureRandom sr = new SecureRandom();
    
        // 从原始密钥数据创建DESKeySpec对象
        DESKeySpec dks = new DESKeySpec(key);
    
        // 创建一个密钥工厂,然后用它把DESKeySpec转换成SecretKey对象
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
        SecretKey securekey = keyFactory.generateSecret(dks);
    
        // Cipher对象实际完成解密操作
        Cipher cipher = Cipher.getInstance(DES);
    
        // 用密钥初始化Cipher对象
        cipher.init(Cipher.DECRYPT_MODE, securekey, sr);
    
        return cipher.doFinal(data);
    }
}

3.RSA加密

package cn.cw.common.utils;

import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.Cipher;


/**
 * ClassName: RSAUtils. <br/>
 * Description: <p>非对称加密算法RSA算法组件</p>
 *              <p>非对称算法一般是用来传送对称加密算法的密钥来使用的,相对于DH算法,RSA算法只需要一方构造密钥,不需要 </p>
 *              <p>大费周章的构造各自本地的密钥对了。DH算法只能算法非对称算法的底层实现。而RSA算法算法实现起来较为简单</p>
 * Date:2019年6月9日. <br/>
 *
 * @author 
 * @version 1.1.0
 * @since 1.7
 */
public class RSAUtils {
    
    /**
     *-定义加密方式
     */
    public static final String KEY_RSA = "RSA";
    
    /**
     * key的长度
     */
    private final static int KEY_SIZE = 1024;
    
    /**
     *-定义公钥关键词
     */
    public static final String KEY_RSA_PUBLICKEY = "RSAPublicKey";
    
    /**
     *-定义私钥关键词
     */
    public static final String KEY_RSA_PRIVATEKEY = "RSAPrivateKey";
    
    /**
     *-定义签名算法
     */
    private final static String KEY_RSA_SIGNATURE = "MD5withRSA";
    
    /**
     *-生成公私密钥对
     */
    public static Map<String, Object> initKey() throws NoSuchAlgorithmException {  
        
        
        //设置密钥对的bit数,越大越安全,但速度减慢,一般使用512或1024
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KEY_RSA);
        keyPairGenerator.initialize(KEY_SIZE);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        
        // 获取公钥,私钥
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        
        // 将密钥对封装为Map
        Map<String, Object> map = new HashMap<String, Object>();
        map.put(KEY_RSA_PUBLICKEY, publicKey);
        map.put(KEY_RSA_PRIVATEKEY, privateKey);
            
        return map;
    }
    
    /**
     * -获取Base64编码的公钥字符串
     * @param map
     * @return
     */
    public static byte[] getPublicKey(Map<String, Object> map) {
        Key key = (Key) map.get(KEY_RSA_PUBLICKEY);
        return key.getEncoded();
    }
    
    /**
     * -获取Base64编码的私钥字符串 
     * @param map
     * @return
     */
    public static byte[] getPrivateKey(Map<String, Object> map) {
        Key key = (Key) map.get(KEY_RSA_PRIVATEKEY);
        return key.getEncoded();
    }
    
    /**
     * -公钥加密
     * @param data
     * @param keyBytes
     * @return
     * @throws Exception
     */
    public static byte[] encryptByPublic(byte[] data, byte[] keyBytes) throws Exception {
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        
        // 取得待加密数据
        KeyFactory factory = KeyFactory.getInstance(KEY_RSA);
        PublicKey publicKey = factory.generatePublic(keySpec);
        
        // 对数据加密  
        Cipher cipher = Cipher.getInstance(factory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        
        return cipher.doFinal(data);
    }
    
    /**
     * -私钥解密
     * @param data
     * @param keyBytes
     * @return
     * @throws Exception
     */
    public static byte[] decryptByPrivate(byte[] data, byte[] keyBytes) throws Exception {
          
        // 获得待解密数据
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory factory = KeyFactory.getInstance(KEY_RSA);
        PrivateKey privateKey = factory.generatePrivate(keySpec);
        
        // 对数据解密
        Cipher cipher = Cipher.getInstance(factory.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        
        return cipher.doFinal(data);
    }

    /**
     * -私钥加密
     * @param data
     * @param keyBytes
     * @return
     * @throws Exception
     */
    public static byte[] encryptByPrivate(byte[] data, byte[] keyBytes) throws Exception {
        
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes); 
        KeyFactory factory = KeyFactory.getInstance(KEY_RSA);  
        PrivateKey privateKey = factory.generatePrivate(keySpec); 
        
        // 对数据加密 
        Cipher cipher = Cipher.getInstance(factory.getAlgorithm());  
        cipher.init(Cipher.ENCRYPT_MODE, privateKey);
        
        return cipher.doFinal(data);  
    }
    
    /**
     * -公钥解密
     * @param data
     * @param keyBytes
     * @return
     * @throws Exception
     */
    public static byte[] decryptByPublic(byte[] data, byte[] keyBytes) throws Exception {
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
            
        // 取得待加密数据
        KeyFactory factory = KeyFactory.getInstance(KEY_RSA);  
        PublicKey publicKey = factory.generatePublic(keySpec);
        
        // 对数据解密  
        Cipher cipher = Cipher.getInstance(factory.getAlgorithm());  
        cipher.init(Cipher.DECRYPT_MODE, publicKey);
        
        return cipher.doFinal(data);  
    }
    
    /**
     * -用私钥对加密数据进行签名
     * @param data
     * @param privateKey
     * @return
     * @throws Exception
     */
    public static String sign(byte[] data, byte[] privateKey) throws Exception {
        PKCS8EncodedKeySpec pkcs = new PKCS8EncodedKeySpec(privateKey);
        
        // 指定的加密算法  
        KeyFactory factory = KeyFactory.getInstance(KEY_RSA);  
        PrivateKey key = factory.generatePrivate(pkcs); 
        
        // 用私钥对信息生成数字签名  
        Signature signature = Signature.getInstance(KEY_RSA_SIGNATURE);  
        signature.initSign(key);  
        signature.update(data);
        
        return Base64Utils.encode(signature.sign());
    }
    
    /**
     * -校验数字签名
     * @param data
     * @param publicKey
     * @param sign
     * @return
     * @throws Exception
     */
    public static boolean verify(byte[] data, byte[] publicKey, String sign) throws Exception {  
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey); 
        
        // 指定的加密算法  
        KeyFactory factory = KeyFactory.getInstance(KEY_RSA);
        PublicKey key = factory.generatePublic(keySpec);
        
        // 用公钥验证数字签名  
        Signature signature = Signature.getInstance(KEY_RSA_SIGNATURE);  
        signature.initVerify(key);  
        signature.update(data); 
        
        return signature.verify(Base64Utils.decode(sign));
    }
    
    public static void main(String[] args) throws Exception {
        Map<String, Object> map = RSAUtils.initKey();
        System.out.println(Base64Utils.encode(RSAUtils.getPrivateKey(map)));
        System.out.println(Base64Utils.encode(RSAUtils.getPublicKey(map)));
    }
}

4.SHA256加密

package cn.cw.common.utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @ProjectName: 
 * @Package: 
 * @ClassName: SHA256Util
 * @Description: SHA256Util加密工具类
 * @Author: 
 * @CreateDate: 2019/3/22 16:28
 */
public class SHA256Util {

    /**
    * @date: 2019/3/22 16:30
    * @author: 
    * @description SHA256加密
    */
    public static String getSHA256StrJava(String str) {
        MessageDigest messageDigest;
        String encodeStr = "";
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(str.getBytes("UTF-8"));
            encodeStr = byte2Hex(messageDigest.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return encodeStr;
    }

    private static String byte2Hex(byte[] bytes) {
        StringBuffer stringBuffer = new StringBuffer();
        String temp = null;
        for (int i = 0; i < bytes.length; i++) {
            temp = Integer.toHexString(bytes[i] & 0xFF);
            if (temp.length() == 1) {
            //1得到一位的进行补0操作
                stringBuffer.append("0");
            }
            stringBuffer.append(temp);
        }
        return stringBuffer.toString();
    }
}

推荐阅读更多精彩内容