Java学习者论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

手机号码,快捷登录

恭喜Java学习者论坛(https://www.javaxxz.com)已经为数万Java学习者服务超过8年了!积累会员资料超过10000G+
成为本站VIP会员,下载本站10000G+会员资源,购买链接:点击进入购买VIP会员
JAVA高级面试进阶视频教程Java架构师系统进阶VIP课程

分布式高可用全栈开发微服务教程

Go语言视频零基础入门到精通

Java架构师3期(课件+源码)

Java开发全终端实战租房项目视频教程

SpringBoot2.X入门到高级使用教程

大数据培训第六期全套视频教程

深度学习(CNN RNN GAN)算法原理

Java亿级流量电商系统视频教程

互联网架构师视频教程

年薪50万Spark2.0从入门到精通

年薪50万!人工智能学习路线教程

年薪50万!大数据从入门到精通学习路线年薪50万!机器学习入门到精通视频教程
仿小米商城类app和小程序视频教程深度学习数据分析基础到实战最新黑马javaEE2.1就业课程从 0到JVM实战高手教程 MySQL入门到精通教程
查看: 732|回复: 0

Java实现的Base64、MD5、3DES三种工具

[复制链接]

该用户从未签到

发表于 2011-9-13 20:13:30 | 显示全部楼层 |阅读模式
[pre]package com.lavasoft.common.security;/** * MD5工具 * * @author leizhimin 2010-6-3 11:10:29 */import java.security.MessageDigest;public class MD5 {    /**     * MD5值计算
* MD5的算法在RFC1321 中定义:     * 在RFC 1321中,给出了Test suite用来检验你的实现是否正确:     * MD5 ("") = d41d8cd98f00b204e9800998ecf8427e     * MD5 ("a") = 0cc175b9c0f1b6a831c399e269772661     * MD5 ("abc") = 900150983cd24fb0d6963f7d28e17f72     * MD5 ("message digest") = f96b697d7cb7938d525a2f31aaf161d0     * MD5 ("abcdefghijklmnopqrstuvwxyz") = c3fcd3d76192e4007dfb496cca67e13b     *     * @param res 源字符串     * @return md5值     */    public final static String MD5(String res) {        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',                'a', 'b', 'c', 'd', 'e', 'f'};        try {            byte[] strTemp = res.getBytes();            MessageDigest mdTemp = MessageDigest.getInstance("MD5");            mdTemp.update(strTemp);            byte[] md = mdTemp.digest();            int j = md.length;            char str[] = new char[j * 2];            int k = 0;            for (int i = 0; i < j; i++) {                byte byte0 = md;                str[k++] = hexDigits[byte0 >>> 4 & 0xf];                str[k++] = hexDigits[byte0 & 0xf];            }            String dd = new String(str);            return dd;        } catch (Exception e) {            return null;        }    }    public static void main(String[] args) {        System.out.println(MD5.MD5(""));        System.out.println(MD5.MD5("a"));        System.out.println(MD5.MD5("abc"));    }}package com.lavasoft.common.security;import java.io.UnsupportedEncodingException;/** * Base64双向加密工具 * * @author leizhimin 2010-6-3 14:10:11 */public class Base64 {    private static char[] base64EncodeChars = new char[]{            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',            'I', 'J', 'K', 'L', 'M', 'N', 'O', &#39',            'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',            'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',            'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',            'o', 'p', 'q', 'r', 's', 't', 'u', 'v',            'w', 'x', 'y', 'z', '0', '1', '2', '3',            '4', '5', '6', '7', '8', '9', '+', '/'};    private static byte[] base64DecodeChars = new byte[]{            -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,            -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,            -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,            52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,            -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,            15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,            -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,            41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1};    /**     * 加密     *     * @param data 明文的字节数组     * @return 密文字符串     */    public static String encode(byte[] data) {        StringBuffer sb = new StringBuffer();        int len = data.length;        int i = 0;        int b1, b2, b3;        while (i < len) {            b1 = data[i++] & 0xff;            if (i == len) {                sb.append(base64EncodeChars[b1 >>> 2]);                sb.append(base64EncodeChars[(b1 & 0x3) << 4]);                sb.append("==");                break;            }            b2 = data[i++] & 0xff;            if (i == len) {                sb.append(base64EncodeChars[b1 >>> 2]);                sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);                sb.append(base64EncodeChars[(b2 & 0x0f) << 2]);                sb.append("=");                break;            }            b3 = data[i++] & 0xff;            sb.append(base64EncodeChars[b1 >>> 2]);            sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);            sb.append(base64EncodeChars[((b2 & 0x0f) << 2) | ((b3 & 0xc0) >>> 6)]);            sb.append(base64EncodeChars[b3 & 0x3f]);        }        return sb.toString();    }    /**     * 解密     *     * @param str 密文     * @return 明文的字节数组     * @throws UnsupportedEncodingException     */    public static byte[] decode(String str) throws UnsupportedEncodingException {        StringBuffer sb = new StringBuffer();        byte[] data = str.getBytes("US-ASCII");        int len = data.length;        int i = 0;        int b1, b2, b3, b4;        while (i < len) {            /* b1 */            do {                b1 = base64DecodeChars[data[i++]];            } while (i < len && b1 == -1);            if (b1 == -1) break;            /* b2 */            do {                b2 = base64DecodeChars                        [data[i++]];            } while (i < len && b2 == -1);            if (b2 == -1) break;            sb.append((char) ((b1 << 2) | ((b2 & 0x30) >>> 4)));            /* b3 */            do {                b3 = data[i++];                if (b3 == 61) return sb.toString().getBytes("iso8859-1");                b3 = base64DecodeChars[b3];            } while (i < len && b3 == -1);            if (b3 == -1) break;            sb.append((char) (((b2 & 0x0f) << 4) | ((b3 & 0x3c) >>> 2)));            /* b4 */            do {                b4 = data[i++];                if (b4 == 61) return sb.toString().getBytes("iso8859-1");                b4 = base64DecodeChars[b4];            } while (i < len && b4 == -1);            if (b4 == -1) break;            sb.append((char) (((b3 & 0x03) << 6) | b4));        }        return sb.toString().getBytes("iso8859-1");    }    public static void main(String[] args) throws UnsupportedEncodingException {        String s = "abcd";        System.out.println("加密前:" + s);        String x = encode(s.getBytes());        System.out.println("加密后:" + x);        String x1 = new String(decode(x));        System.out.println("解密后:" + x1);    }}package com.lavasoft.common.security;import sun.misc.BASE64Decoder;import sun.misc.BASE64Encoder;import javax.crypto.Cipher;import javax.crypto.KeyGenerator;import java.security.Key;import java.security.SecureRandom;/** * 使用3DES加密与解密,可对byte[],String类型进行加密与解密 密文可使用String,byte[]存储. * * @author leizhimin 2010-6-3 11:10:54 */public class ThreeDES {    private Key key;        //密钥    /**     * 根据参数生成KEY     *     * @param strKey 密钥字符串     */    public void getKey(String strKey) {        try {            KeyGenerator _generator = KeyGenerator.getInstance("DES");            _generator.init(new SecureRandom(strKey.getBytes()));            this.key = _generator.generateKey();            _generator = null;        } catch (Exception e) {            e.printStackTrace();        }    }    /**     * 加密String明文输入,String密文输出     *     * @param strMing String明文     * @return String密文     */    public String getEncString(String strMing) {        byte[] byteMi = null;        byte[] byteMing = null;        String strMi = "";        BASE64Encoder base64en = new BASE64Encoder();        try {            byteMing = strMing.getBytes("UTF8");            byteMi = this.getEncCode(byteMing);            strMi = base64en.encode(byteMi);        } catch (Exception e) {            e.printStackTrace();        } finally {            base64en = null;            byteMing = null;            byteMi = null;        }        return strMi;    }    /**     * 解密 以String密文输入,String明文输出     *     * @param strMi String密文     * @return String明文     */    public String getDesString(String strMi) {        BASE64Decoder base64De = new BASE64Decoder();        byte[] byteMing = null;        byte[] byteMi = null;        String strMing = "";        try {            byteMi = base64De.decodeBuffer(strMi);            byteMing = this.getDesCode(byteMi);            strMing = new String(byteMing, "UTF8");        } catch (Exception e) {            e.printStackTrace();        } finally {            base64De = null;            byteMing = null;            byteMi = null;        }        return strMing;    }    /**     * 加密以byte[]明文输入,byte[]密文输出     *     * @param byteS byte[]明文     * @return byte[]密文     */    private byte[] getEncCode(byte[] byteS) {        byte[] byteFina = null;        Cipher cipher;        try {            cipher = Cipher.getInstance("DES");            cipher.init(Cipher.ENCRYPT_MODE, key);            byteFina = cipher.doFinal(byteS);        } catch (Exception e) {            e.printStackTrace();        } finally {            cipher = null;        }        return byteFina;    }    /**     * 解密以byte[]密文输入,以byte[]明文输出     *     * @param byteD byte[]密文     * @return byte[]明文     */    private byte[] getDesCode(byte[] byteD) {        Cipher cipher;        byte[] byteFina = null;        try {            cipher = Cipher.getInstance("DES");            cipher.init(Cipher.DECRYPT_MODE, key);            byteFina = cipher.doFinal(byteD);        } catch (Exception e) {            e.printStackTrace();        } finally {            cipher = null;        }        return byteFina;    }    public static void main(String[] args) {        ThreeDES des = new ThreeDES();  // 实例化一个对像        des.getKey("abcdefgasiainfo");  // 生成密匙        String strEnc = des.getEncString("abc");// 加密字符串,返回String的密文        System.out.println(strEnc);        String strDes = des.getDesString(strEnc);// 把String 类型的密文解密        System.out.println(strDes);    }}
[/pre]
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|手机版|Java学习者论坛 ( 声明:本站资料整理自互联网,用于Java学习者交流学习使用,对资料版权不负任何法律责任,若有侵权请及时联系客服屏蔽删除 )

GMT+8, 2024-5-4 18:52 , Processed in 0.387344 second(s), 46 queries .

Powered by Discuz! X3.4

© 2001-2017 Comsenz Inc.

快速回复 返回顶部 返回列表