android 三种常用的加密方式

android应用中常用的加密方式有三种:MD5,AES,RSA。在进行实际的开发过程中,一般是几种加密方式配合使用,这样加密效果会更好,被破解的概率会越小。下面我们就分别讲一下三种加密方式的实现过程。

一、MD5

MD5本质是一种散列函数,用以提供消息的完整性保护。

特点:

1.压缩性:任意长度的数据,算出的MD5值长度都是固定的;

2.容易计算:从原数据计算出MD5值很容易;

3.抗修改性:对原数据进行任何改动,哪怕只修改1个字节,所得到的MD5值都有很大的区别;

4.强抗碰撞:已知原数据和其MD5值,想找到一个具有相同MD5值的数据(及伪造数据)是非常困难的;

5.不可逆:MD5理论上是不可逆的(但是现在已经可以暴力破解了)。

使用场景:

1.验证密码:只要算法不变,就能和服务器上的MD5匹配;

2.文件完整性的校验:当下载一个文件时,服务器返回的信息包括这个文件的md5,在本地下载完毕时进行md5加密,将两个md5值进行比较,如果一致则说明文件完整没有丢包现象。

工具类代码:

package comvoice.example.zhangbin.md5codedemo.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

//MD5加密
public class MD5Utils {

    //加密字符串
    public String getMD5Code(String info){
        try {
            MessageDigest md5=MessageDigest.getInstance("MD5");
            md5.update(info.getBytes("utf-8"));
            byte[]encryption=md5.digest();
            StringBuffer stringBuffer=new StringBuffer();
            for(int i=0;i<encryption.length;i++){
                if(Integer.toHexString(0xff &encryption[i]).length()==1){
                    stringBuffer.append("0").append(Integer.toHexString(0xff&encryption[i]));
                }else {
                    stringBuffer.append(Integer.toHexString(0xff&encryption[i]));
                }
            }
            return stringBuffer.toString();
        } catch (Exception e) {
//            e.printStackTrace();
            return "";
        }
    }
    //加密文件
    public static String md5ForFile(File file){
        int buffersize = 1024;
        FileInputStream fis = null;
        DigestInputStream dis = null;

        try {
            //创建MD5转换器和文件流
            MessageDigest messageDigest =MessageDigest.getInstance("MD5");
            fis = new FileInputStream(file);
            dis = new DigestInputStream(fis,messageDigest);

            byte[] buffer = new byte[buffersize];
            //DigestInputStream实际上在流处理文件时就在内部就进行了一定的处理
            while (dis.read(buffer) > 0);

            //通过DigestInputStream对象得到一个最终的MessageDigest对象。
            messageDigest = dis.getMessageDigest();

            // 通过messageDigest拿到结果,也是字节数组,包含16个元素
            byte[] array = messageDigest.digest();
            // 同样,把字节数组转换成字符串
            StringBuilder hex = new StringBuilder(array.length * 2);
            for (byte b : array) {
                if ((b & 0xFF) < 0x10){
                    hex.append("0");
                }
                hex.append(Integer.toHexString(b & 0xFF));
            }
            return hex.toString();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

}

二、RSA加密

RSA加密算法是一种非对称加密算法,非对称加密算法需要两个密钥:公共密钥和私有密钥。公钥和私钥是配对的,用公钥加密的数据只有配对的私钥才能解密。

RSA对加密数据的长度有限制,一般为密钥的长度值-11,要加密较长的数据,可以采用数据截取的方法,分段加密。

使用场景:

文件或数据在本地使用公钥或私钥加密,加密后的数据传送到服务器,服务器使用同一套密钥中的私钥或者公钥进行解密。

package comvoice.example.zhangbin.md5codedemo.utils;

import android.util.Base64;

import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;

public class RSAUtils {
    //构建Cipher实例时所传入的的字符串,默认为"RSA/NONE/PKCS1Padding"
    private static String sTransform = "RSA/NONE/PKCS1Padding";

    //进行Base64转码时的flag设置,默认为Base64.DEFAULT
    private static int sBase64Mode = Base64.DEFAULT;
    //初始化方法,设置参数
    public static void init(String transform,int base64Mode){
        sTransform = transform;
        sBase64Mode = base64Mode;
    }
    //产生密钥对
    public static KeyPair generateRSAKeyPair(int keyLength){
        KeyPair keyPair=null;
        try {
            KeyPairGenerator keyPairGenerator=KeyPairGenerator.getInstance("RSA");
            //设置密钥长度
            keyPairGenerator.initialize(keyLength);
            //产生密钥对
            keyPair=keyPairGenerator.generateKeyPair();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return keyPair;
    }

    /**
     * 加密或解密数据的通用的方法,srcData:待处理的数据;key:公钥或者私钥,mode指
     * 加密还是解密,值为Cipher.ENCRYPT_MODE或者Cipher.DECRYPT_MODE
     */
    public static byte[]processDAta(byte[]srcData, Key key,int mode){
        //用来保存处理的结果
        byte[]resultBytes=null;
        //构建Cipher对象,需要传入一个字符串,格式必须为"algorithm/mode/padding"或者"algorithm/",意为"算法/加密模式/填充方式"
        try {
            Cipher cipher=Cipher.getInstance("RSA/NONE/PKCS1Padding");
            //初始化Cipher,mode指定是加密还是解密,key为公钥或密钥
            cipher.init(mode,key);
            //处理数据
            resultBytes=cipher.doFinal(srcData);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultBytes;
    }
    //使用公钥加密数据,结果用Base64转码
    public static String encryptDataByPublicKey(byte[]srcData, PublicKey publicKey){
        byte[]resultBytes=processDAta(srcData,publicKey,Cipher.ENCRYPT_MODE);
        return Base64.encodeToString(resultBytes,sBase64Mode);
    }
    //使用私钥解密,结果用Base64转码
    public static byte[]decryptDataByPrivate(String encryptedData, PrivateKey privateKey){
        byte[]bytes=Base64.decode(encryptedData,sBase64Mode);
        return processDAta(bytes,privateKey,Cipher.DECRYPT_MODE);
    }

    //使用私钥解密,返回解码数据
    public static String decryptToStrByPrivate(String encryptedData,PrivateKey privateKey){
        return new String(decryptDataByPrivate(encryptedData,privateKey));
    }

}

三、AES加密

AES加密是一种高级加密标准,是一种区块加密标准。它是一个对称密码,就是说加密和解密用相同的密钥。WPA/WPA2经常用的加密方式就是AES加密算法。

示意图:

工具类代码:

package comvoice.example.zhangbin.md5codedemo.utils;

import java.io.UnsupportedEncodingException;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class AESUtils3 {
    /*   算法/模式/填充 */
    private static final String CipherMode = "AES/ECB/PKCS5Padding";

    /*  创建密钥  */
    private static SecretKeySpec createKey(String password) {
        byte[] data = null;
        if (password == null) {
            password = "";
        }
        StringBuffer sb = new StringBuffer(32);
        sb.append(password);
        while (sb.length() < 32) {
            sb.append("0");
        }
        if (sb.length() > 32) {
            sb.setLength(32);
        }

        try {
            data = sb.toString().getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return new SecretKeySpec(data, "AES");
    }

    /* 加密字节数据  */
    public static byte[] encrypt(byte[] content, String password) {
        try {
            SecretKeySpec key = createKey(password);
            System.out.println(key);
            Cipher cipher = Cipher.getInstance(CipherMode);
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] result = cipher.doFinal(content);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /*加密(结果为16进制字符串)  */
    public static String encrypt(String content, String password) {
        byte[] data = null;
        try {
            data = content.getBytes("UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        data = encrypt(data, password);
        String result = byte2hex(data);
        return result;
    }

    /*解密字节数组*/
    public static byte[] decrypt(byte[] content, String password) {
        try {
            SecretKeySpec key = createKey(password);
            Cipher cipher = Cipher.getInstance(CipherMode);
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] result = cipher.doFinal(content);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /*解密16进制的字符串为字符串  */
    public static String decrypt(String content, String password) {
        byte[] data = null;
        try {
            data = hex2byte(content);
        } catch (Exception e) {
            e.printStackTrace();
        }
        data = decrypt(data, password);
        if (data == null) return null;
        String result = null;
        try {
            result = new String(data, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }

    /*字节数组转成16进制字符串  */
    public static String byte2hex(byte[] b) { // 一个字节的数,
        StringBuffer sb = new StringBuffer(b.length * 2);
        String tmp = "";
        for (int n = 0; n < b.length; n++) {
            // 整数转成十六进制表示
            tmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
            if (tmp.length() == 1) {
                sb.append("0");
            }
            sb.append(tmp);
        }
        return sb.toString().toUpperCase(); // 转成大写
    }

    /*将hex字符串转换成字节数组 */
    private static byte[] hex2byte(String inputString) {
        if (inputString == null || inputString.length() < 2) {
            return new byte[0];
        }
        inputString = inputString.toLowerCase();
        int l = inputString.length() / 2;
        byte[] result = new byte[l];
        for (int i = 0; i < l; ++i) {
            String tmp = inputString.substring(2 * i, 2 * i + 2);
            result[i] = (byte) (Integer.parseInt(tmp, 16) & 0xFF);
        }
        return result;
    }
}

猜你喜欢

转载自blog.csdn.net/u011897782/article/details/81163387