博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Android 加密解密
阅读量:7212 次
发布时间:2019-06-29

本文共 13433 字,大约阅读时间需要 44 分钟。

  hot3.png

1.

public SecretKey secretKey;    public byte[] encrypt;    public KeyPair keyPair;    public byte[] rsaEncrypt;    /**     * BASE 64     *     * @param view     */    public void base64encode(View view) {        //文本编码        base64encoder = BASE64.base64encoder(STR_BASE64);        Log.e(TAG, base64encoder);    }    public void base64decode(View view) {        if (base64encoder != null) {            //文本解码            String base64decode = BASE64.base64decode(base64encoder);            Log.e(TAG, base64decode);        }    }    /**     * MD5s     * @param view     */    public void md5(View view) {        byte[] md5 = MD5.getMD5(STR_MD5.getBytes());        StringBuilder sb  = new StringBuilder();        for (byte b : md5) {            sb.append(b);        }        Log.e(TAG, "md5:"+sb.toString());        String md5Str = CommUtils.bytesConvertToHexString(md5);        Log.e(TAG, "md5:"+md5Str);    }    /**     * SHA     * @param view     */    public void sha(View view) {        try {            byte[] bytes = SHA.encodeSHA(STR_SHA.getBytes());            byte[] bytes256 = SHA.encodeSHA256(STR_SHA.getBytes());            byte[] bytes384 = SHA.encodeSHA384(STR_SHA.getBytes());            byte[] bytes512 = SHA.encodeSHA512(STR_SHA.getBytes());            String bytesStr = CommUtils.bytesConvertToHexString(bytes);            String bytes256Str = CommUtils.bytesConvertToHexString(bytes256);            String bytes384Str = CommUtils.bytesConvertToHexString(bytes384);            String bytes512Str = CommUtils.bytesConvertToHexString(bytes512);            Log.e(TAG,"SIZE:"+bytesStr.length()+" "+bytesStr+" length:"+bytes.length);            Log.e(TAG,"SIZE:"+bytes256Str.length()+" "+bytes256Str+" length:"+bytes256.length);            Log.e(TAG,"SIZE:"+bytes384Str.length()+" "+bytes384Str+" length:"+bytes384.length);            Log.e(TAG,"SIZE:"+bytes512Str.length()+" "+bytes512Str+" length:"+bytes512.length);           /* StringBuilder sb  = new StringBuilder();            for (byte b : bytes512) {                sb.append(b);            }            Log.e(TAG,"SIZE:"+bytes512Str.length()+" "+bytes512Str+" length:"+sb.length());*/        } catch (Exception e) {            e.printStackTrace();        }    }    /**     * DES     * @param view     */    public void desInit(View view) {        //初始化密钥        try {            secretKey = DES.initKey();        } catch (Exception e) {            e.printStackTrace();        }    }    public void desEncrypt(View view) {        //加密        if (secretKey != null) {            try {                //第一个参数 字节数组,密钥                encrypt = DES.encrypt(STR_DES.getBytes(), secretKey);                String encryptStr = CommUtils.bytesConvertToHexString(encrypt);                Log.e(TAG,"encryptStr:"+encryptStr);            } catch (Exception e) {                e.printStackTrace();            }        }else{            Toast.makeText(this, "请初始化密钥", Toast.LENGTH_SHORT).show();        }    }    public void desDecrypt(View view) {        //解密        if (secretKey != null) {            try {                byte[] decrypt = DES.decrypt(encrypt, secretKey);                Log.e(TAG,"decryptStr:"+new String(decrypt));            } catch (Exception e) {                e.printStackTrace();            }        }else{            Toast.makeText(this, "请初始化密钥", Toast.LENGTH_SHORT).show();        }    }    /**     * RSA     * @param view     */    public void rsaInit(View view) {        //rsa 初始化        try {            keyPair = RSA.initKey();        } catch (NoSuchAlgorithmException e) {            e.printStackTrace();        }    }    public void rsaEncrypt(View view) {        if (keyPair != null) {            //rsa 加密            RSAPublicKey rsaPublicKey = RSA.getRSAPublicKey(keyPair);   //获取公钥//            RSAPrivateKey rsaPrivateKey = RSA.getRSAPrivateKey(keyPair);            try {                rsaEncrypt = RSA.encrypt(STR_RSA.getBytes(), rsaPublicKey.getEncoded());//                rsaEncrypt = RSA.encrypt(STR_RSA.getBytes(), rsaPrivateKey.getEncoded());                String encryptStr = CommUtils.bytesConvertToHexString(rsaEncrypt);                Log.e(TAG,"encryptStr:"+encryptStr);            } catch (Exception e) {                e.printStackTrace();            }        }else{            Toast.makeText(this, "请初始化密钥", Toast.LENGTH_SHORT).show();        }    }    public void rsaDecrypt(View view) {        //rsa 解密        if (keyPair != null) {            RSAPrivateKey rsaPrivateKey = RSA.getRSAPrivateKey(keyPair);//            RSAPublicKey rsaPublicKey = RSA.getRSAPublicKey(keyPair);            try {                byte[] decrypt = RSA.decrypt(rsaEncrypt, rsaPrivateKey.getEncoded());//                byte[] decrypt = RSA.decrypt(rsaEncrypt, rsaPublicKey.getEncoded());                Log.e(TAG,"decrypt:"+new String(decrypt));            } catch (Exception e) {                e.printStackTrace();            }        }else{            Toast.makeText(this, "请初始化密钥", Toast.LENGTH_SHORT).show();        }    }

2.BASE64

public class BASE64 {    /***     * BASE64编码     *     * @param data 待编码的数据     * @return 编码后的数据     */    public static String base64encoder(String data) {        byte[] b = Base64.encode(data.getBytes(), Base64.DEFAULT);        return new String(b);    }    /**     * Base64解码     *     * @param data 待解码的数据     * @return 解码后的数据     */    public static String base64decode(String data) {        byte[] b = Base64.decode(data.getBytes(), Base64.DEFAULT);        return new String(b);    }}

3.DES

public class DES {    //加密方式    public final static String ALGORITHM = "DES";    //密码,长度要是8的倍数  自定义    private static  String password = "12345678";    private static SecureRandom random;//    private static SecretKey securekey;    /**     * 初始化密钥     * @throws InvalidKeyException     * @throws NoSuchAlgorithmException     * @throws InvalidKeySpecException     */    public static SecretKey initKey() throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException {        random = new SecureRandom();        DESKeySpec desKey = new DESKeySpec(password.getBytes());        //创建一个密匙工厂,然后用它把DESKeySpec进行转换        SecretKeyFactory keyFactory =  SecretKeyFactory.getInstance(ALGORITHM);        SecretKey securekey = keyFactory.generateSecret(desKey);        return securekey;    }    /**     * DES加密     *     * @param data //待加密的数据     * @return //加密后的数据     * @throws  NoSuchAlgorithmException     * @throws  InvalidKeyException     * @throws  InvalidKeySpecException     * @throws  NoSuchPaddingException     * @throws  BadPaddingException     * @throws  IllegalBlockSizeException     */    public static byte[] encrypt(byte[] data,SecretKey securekey) throws NoSuchAlgorithmException, InvalidKeyException, InvalidKeySpecException, NoSuchPaddingException, BadPaddingException, IllegalBlockSizeException {        try{            //Cipher对象实际完成加密操作            Cipher cipher = Cipher.getInstance(ALGORITHM);            //用密匙初始化Cipher对象  编码模式            cipher.init(Cipher.ENCRYPT_MODE, securekey, random);            //现在,获取数据并加密            //正式执行加密操作            return cipher.doFinal(data);        }catch(Throwable e){            e.printStackTrace();        }        return null;    }    /**     * DES数据解密     *     * @param data 待解密的数据     * @throws  NoSuchAlgorithmException     * @throws  InvalidKeyException     * @throws  InvalidKeySpecException     * @throws  NoSuchPaddingException     * @throws  BadPaddingException     * @throws  IllegalBlockSizeException     */    public static byte[] decrypt(byte[] data,SecretKey securekey) throws NoSuchAlgorithmException, InvalidKeyException, InvalidKeySpecException, NoSuchPaddingException, BadPaddingException, IllegalBlockSizeException {        // Cipher对象实际完成解密操作        Cipher cipher = Cipher.getInstance(ALGORITHM);        // 用密匙初始化Cipher对象   解码模式        cipher.init(Cipher.DECRYPT_MODE, securekey, random);        // 真正开始解密操作        return cipher.doFinal(data);    }}

4.MD5

/** * 消息摘要 * MD5算法是典型的消息摘要算法,其前身有MD2,MD3和,MD4算法。 * 不论哪种MD算法,它们都需要获得以讹随 机长度的信息并产生以一个128位的信息摘要。 * 如果将这个128位的信息摘要转换为十六进制,就可以得到一 个32位的字符串, * 因此我们见到的大部分MD5算法的指纹都是32位十六进制的字符串。 * 

* 特点:消息摘要的主要特点是对同一段数据做多次摘要处理后,其摘要值完全一致。 */public class MD5 { /** * 获得数据的MD5编码 * * @param data 待处理的数据 * @return 加密后的MD5值 */ public static byte[] getMD5(byte[] data) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(data); return md.digest(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; }}

5.RSA

public class RSA {    /**     * 算法名称     */    public static final String KEY_ALGORITHM = "RSA";   //算法    /**     * RSA密钥长度     * 默认为1024位     * 密钥长度必须为64的倍数 * 范围在512~65536之间     */    private static final int KEY_SIZE = 1024;    /**     * 生成密钥对     *     * @return 密钥对对象     * @throws NoSuchAlgorithmException     */    public static KeyPair initKey() throws NoSuchAlgorithmException {        //实例化密钥对生成器        KeyPairGenerator generator = KeyPairGenerator.getInstance(KEY_ALGORITHM);        //初始化密钥对生成器        generator.initialize(KEY_SIZE);        //生成密钥对        return generator.generateKeyPair();    }    /**     * 获得密钥对中公钥     * @param pair 密钥对 *     * @return     */    public static RSAPublicKey getRSAPublicKey(KeyPair pair){        RSAPublicKey key = (RSAPublicKey)pair.getPublic();        //获得公钥编码        byte[] encoded = key.getEncoded();        return key;    }    /**     * 获得密钥对中私钥     * @param pair 密钥对 *     * @return     */    public static RSAPrivateKey getRSAPrivateKey(KeyPair pair){        RSAPrivateKey key = (RSAPrivateKey)pair.getPrivate();        //获得私钥编码        byte[] encoded = key.getEncoded();        return key;    }    /**     * RSA加密     * @param data  待解密的数据     * @param key   公钥     * @return      解密后的数据     * @throws NoSuchAlgorithmException     * @throws InvalidKeySpecException     * @throws NoSuchPaddingException     * @throws InvalidKeyException     * @throws BadPaddingException     * @throws IllegalBlockSizeException     */    public static byte[] encrypt(byte[] data, byte[] key) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {        //取得私钥        X509EncodedKeySpec spec = new X509EncodedKeySpec(key);        KeyFactory factory = KeyFactory.getInstance(KEY_ALGORITHM);        //生成私钥        PublicKey publicKey = factory.generatePublic(spec);        //对数据加密        Cipher cipher = Cipher.getInstance(factory.getAlgorithm());        cipher.init(Cipher.ENCRYPT_MODE, publicKey);        return cipher.doFinal(data);    }    /**     * RSA解密     *     * @param data 待解密的数据     * @param key  私钥     * @return 解密后的数据     * @throws NoSuchAlgorithmException     * @throws InvalidKeySpecException     * @throws NoSuchPaddingException     * @throws InvalidKeyException     * @throws BadPaddingException     * @throws IllegalBlockSizeException     */    public static byte[] decrypt(byte[] data, byte[] key) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {        //取得私钥        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(key);        KeyFactory factory = KeyFactory.getInstance(KEY_ALGORITHM);        //生成私钥        PrivateKey privateKey = factory.generatePrivate(spec);        //对数据解密        Cipher cipher = Cipher.getInstance(factory.getAlgorithm());        cipher.init(Cipher.DECRYPT_MODE, privateKey);        return cipher.doFinal(data);    }}

6.SHA

/** * 消息摘要 * SHA算法基于MD4算法基础之上,作为MD算法的继任者。 * SHA与MD算法不同之处在于摘要长度,SHA算法的 摘要长度更长,安全性更高。 */public class SHA {    /**     * SHA-1消息摘要     *     * @param data 待处理的数据     * @return 消息摘要     * @throws NoSuchAlgorithmException     */    public static byte[] encodeSHA(byte[] data) throws NoSuchAlgorithmException {        MessageDigest md = MessageDigest.getInstance("SHA");        return md.digest(data);    }    /**     * SHA-256消息摘要     *     * @param data 待处理的数据     * @return 消息摘要     * @throws NoSuchAlgorithmException     */    public static byte[] encodeSHA256(byte[] data) throws NoSuchAlgorithmException {        MessageDigest md = MessageDigest.getInstance("SHA-256");        return md.digest(data);    }    /**     * SHA-384消息摘要     *     * @param data 待处理的数据     * @return 消息摘要     * @throws NoSuchAlgorithmException     */    public static byte[] encodeSHA384(byte[] data) throws NoSuchAlgorithmException {        MessageDigest md = MessageDigest.getInstance("SHA-384");        return md.digest(data);    }    /**     * SHA-512消息摘要     *     * @param data 待处理的数据     * @return 消息摘要     * @throws NoSuchAlgorithmException     */    public static byte[] encodeSHA512(byte[] data) throws NoSuchAlgorithmException {        MessageDigest md = MessageDigest.getInstance("SHA-512");        return md.digest(data);    }}

7.工具类

public class CommUtils {    /**     * byte数组 转 16进制     * @param bytes     * @return     */    public static String bytesConvertToHexString(byte[] bytes) {        StringBuffer sb = new StringBuffer();        for (byte aByte : bytes) {            String s = Integer.toHexString(0xff & aByte);            if (s.length() == 1) {                sb.append("0" + s);            } else {                sb.append(s);            }        }        return sb.toString();    }}

 

 

 

转载于:https://my.oschina.net/glfei/blog/2961201

你可能感兴趣的文章
我为什么晚上写代码?
查看>>
React+Redux开发实录(一)搭建工程脚手架
查看>>
我来阅读lodash源码——Math(一)
查看>>
Laravel 5.5 使用 Passport 实现 Auth 认证
查看>>
用python写通用restful api service(一)
查看>>
javascript this指针详解
查看>>
Hystrix:HystrixCollapser请求合并
查看>>
three.js 入门详解(一)
查看>>
Android基础之Java接口
查看>>
Angular开发实践(一):环境准备及框架搭建
查看>>
Vue2 源码漫游(二)
查看>>
微信浏览器下拉黑边的终极解决方案---wScroollFix
查看>>
我是如何学会爱上 Vim 的
查看>>
小tips:JS中typeof与instanceof用法
查看>>
阿里云Ecs挂载云盘
查看>>
《Kotlin项目实战开发》第1章 Kotlin是什么
查看>>
基于 react, redux 最佳实践构建的 2048
查看>>
云栖大会看技术人成长之路
查看>>
从零搭建React全家桶框架教程
查看>>
Windows command tools
查看>>