首页 > 代码库 > Java加密算法

Java加密算法

JDK中带有部分加密算法的实现类,主要的是java.security和javax.crypto包下的类,还可以使用Bouncy Castle(丰富JDK中加密算法的不足)jar包是:bcprov-jdk15on-1.57.jar和Commons Codec(简化JDK中加密的操作)jar包是:commons-codec-1.10.jar

Base64

Base64用于网络中传输的数据进行编码,严格意义上属于编码的格式,有64个字符的对应的编码,Base64就是将内容按照该格式进行编码。可以对数据编码和解码,是可逆的,安全度较低,不过,也可以作为最基础最简单的加密算法用于加密要求较弱的情况

Base64可以使用JDk中自带的类实现,还可以使用Bouncy Castle(简称bc)或Commons Codec(简称cc)实现

加密数据:

private static String src="http://www.mamicode.com/Hello Base64";

 

导入的类:

import java.io.IOException;import org.apache.commons.codec.binary.Base64;import sun.misc.BASE64Decoder;import sun.misc.BASE64Encoder;

 

JDk实现主要使用用BASE64Encoder和BASE64Decoder类的方法(注意在Eclipse中使用JDK的Base64可能会出现找不到的问题,是因为Base64Encoder并不属于JDK标准库范畴,但是又包含在了JDK中,需要我们手动导入\jre\lib目录下的rt.jar包即可):

    public static void jdkBase64(){        try {            BASE64Encoder encoder=new BASE64Encoder();            String encode = encoder.encode(src.getBytes());            System.out.println("encode: "+encode);                        BASE64Decoder decoder=new BASE64Decoder();            String decode=new String(decoder.decodeBuffer(encode));            System.out.println("decode: "+decode);        } catch (IOException e) {            e.printStackTrace();        }    }

 

bc实现主要是用Base64类的方法:

    public static void bouncybastleBase64(){        byte[] encode = org.bouncycastle.util.encoders.Base64.encode(src.getBytes());        System.out.println("encode: "+new String(encode));                byte[] decode = org.bouncycastle.util.encoders.Base64.decode(encode);        System.out.println("decode: "+new String(decode));    }

 

cc实现也是用Base64类,不过与bc的是不一样的,不同包中的类,只是名字一样:

    public static void commonscodecBase64(){        byte[] encode=Base64.encodeBase64(src.getBytes());        System.out.println("encode: "+new String(encode));  //需要转化为String                byte[] decode = Base64.decodeBase64(encode);        System.out.println("decode: "+new String(decode));    }

 

摘要算法

摘要算法主要分为MD,SHA和Hmac算法,摘要算法其实是用于效验数据完整性的,我们在下载某些文件时,会有MD5和SHA1值提供我们效验下载的文件是否完整,可以用于根据数据生成其唯一的摘要值,无法根据摘要值知道原数据,属于不可逆的

MD:

技术分享

加密数据:

private static String src="http://www.mamicode.com/Hello MD";

 

导入的类:

import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;import java.security.Provider;import java.security.Security;import org.apache.commons.codec.binary.Hex;import org.apache.commons.codec.digest.DigestUtils;import org.bouncycastle.crypto.Digest;import org.bouncycastle.crypto.digests.MD2Digest;import org.bouncycastle.crypto.digests.MD4Digest;import org.bouncycastle.crypto.digests.MD5Digest;import org.bouncycastle.jce.provider.BouncyCastleProvider;

 

JDK有MD2和MD5的实现,使用的是MessageDigest类,而没有MD4的实现:

    public static void jdkMD5(){        try {            MessageDigest md=MessageDigest.getInstance("MD5");            byte[] digest = md.digest(src.getBytes());            System.out.println("JDK MD5: "+Hex.encodeHexString(digest));           //使用的是cc中带的Hex需要转换为十六进制        } catch (NoSuchAlgorithmException e) {            e.printStackTrace();        }            }        public static void jdkMD2(){        try {            MessageDigest md=MessageDigest.getInstance("MD2");            byte[] digest = md.digest(src.getBytes());            System.out.println("JDK MD2: "+Hex.encodeHexString(digest));           } catch (NoSuchAlgorithmException e) {            e.printStackTrace();        }            }

 

而bc这三种都有,使用的是Digest 类:

    public static void bcMD4(){        //方式一//        Digest digest=new MD4Digest();//        digest.update(src.getBytes(), 0, src.getBytes().length);//        byte[] md4Bytes=new byte[digest.getDigestSize()];//        digest.doFinal(md4Bytes, 0);//        System.out.println("BC MD4: "+org.bouncycastle.util.encoders.Hex.toHexString(md4Bytes));                      //方式二        try {            Security.addProvider(new BouncyCastleProvider());            MessageDigest md=MessageDigest.getInstance("MD4");            byte[] digest = md.digest(src.getBytes());            System.out.println("BC MD4: "+Hex.encodeHexString(digest));        } catch (NoSuchAlgorithmException e) {            e.printStackTrace();        }    }        public static void bcMD5(){        Digest digest=new MD5Digest();        digest.update(src.getBytes(), 0, src.getBytes().length);        byte[] md4Bytes=new byte[digest.getDigestSize()];        digest.doFinal(md4Bytes, 0);        System.out.println("BC MD5: "+org.bouncycastle.util.encoders.Hex.toHexString(md4Bytes));        //bc中带的Hex    }        public static void bcMD2(){        Digest digest=new MD2Digest();        digest.update(src.getBytes(), 0, src.getBytes().length);        byte[] md4Bytes=new byte[digest.getDigestSize()];        digest.doFinal(md4Bytes, 0);        System.out.println("BC MD2: "+org.bouncycastle.util.encoders.Hex.toHexString(md4Bytes));    }

 

cc和JDK是一样的,毕竟是对JDK加密的简化,直接使用DigestUtils中的方法,很简单,而且前两种方法还需要将MD值转换为十六进制,cc直接就帮我们转了:

    public static void ccMD2(){        //有方法直接就可以转换十六进制        System.out.println("CC MD2: "+DigestUtils.md2Hex(src.getBytes()));    }        public static void ccMd5(){        System.out.println("CC MD5: "+DigestUtils.md5Hex(src.getBytes()));    }

 

SHA:

这里只是使用SHA-1,其他类型类似

技术分享

加密数据:

private static String src="http://www.mamicode.com/Hello SHA";

 

要导入的类:

import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;import org.apache.commons.codec.binary.Hex;import org.apache.commons.codec.digest.DigestUtils;import org.bouncycastle.crypto.Digest;import org.bouncycastle.crypto.digests.SHA1Digest;import sun.security.provider.SHA;

 

JDK实现方式(同样是使用MessageDigest):

    public static void jdkSHA1(){        MessageDigest digest;        try {            digest = MessageDigest.getInstance("SHA");            digest.update(src.getBytes());            System.out.println("JDK SHA1: "+Hex.encodeHexString(digest.digest()));        } catch (NoSuchAlgorithmException e) {            e.printStackTrace();        }    }

 

bc的实现方式(同样是Digest 类):

    public static void mcSHA1(){        Digest digest=new SHA1Digest();        digest.update(src.getBytes(),0,src.getBytes().length);        byte[] sha1Byte1=new byte[digest.getDigestSize()];        digest.doFinal(sha1Byte1, 0);        System.out.println("MC SHA1:"+org.bouncycastle.util.encoders.Hex.toHexString(sha1Byte1));    }

 

cc的实现方式:

    public static void ccsha(){        System.out.println("CC sha1:"+DigestUtils.sha1Hex(src));    }

 

Hmac(含有密钥的摘要算法,也有简称mac,密钥不同摘要也不同):

技术分享

要加密的数据:

private static String src="http://www.mamicode.com/Hello HMAC";

 

要导入的类:

import javax.crypto.KeyGenerator;import javax.crypto.Mac;import javax.crypto.SecretKey;import javax.crypto.spec.SecretKeySpec;import org.apache.commons.codec.binary.Hex;import org.bouncycastle.crypto.digests.MD5Digest;import org.bouncycastle.crypto.macs.HMac;import org.bouncycastle.crypto.params.KeyParameter;

 

JDK的实现方式:

    public static void jdkHmacMD5(){        try {            KeyGenerator keyGenerator=KeyGenerator.getInstance("HmacMD5");  //初始化KeyGenerator            SecretKey secretKey=keyGenerator.generateKey(); //产生密钥            //byte[] key=secretKey.getEncoded();     //获得密钥(默认生成)                        byte[] key=Hex.decodeHex(new char[]{‘a‘,‘a‘,‘a‘,‘a‘,‘a‘,‘a‘,‘a‘,‘a‘,‘a‘,‘a‘});  //手动生成密钥(十位)                        SecretKey secretKey2=new SecretKeySpec(key, "HmacMD5"); //还原密钥            Mac mac=Mac.getInstance(secretKey2.getAlgorithm());  //实例化mac            //初始化mac            mac.init(secretKey2);            byte[] hmacMD5Bytes=mac.doFinal(src.getBytes());            System.out.println("jdk hmacMD5: "+Hex.encodeHexString(hmacMD5Bytes));        } catch (Exception e) {            e.printStackTrace();        }     }

 

bc的实现方式:

    public static void bcHmacMd5(){        HMac hMac=new HMac(new MD5Digest());        hMac.init(new KeyParameter(org.bouncycastle.util.encoders.Hex.decode("aaaaaaaaaa")));  //需要十位密钥        hMac.update(src.getBytes(),0,src.getBytes().length);                byte[] hmacMD5=new byte[hMac.getMacSize()];        hMac.doFinal(hmacMD5, 0);        System.out.println("bc hmacMD5: "+org.bouncycastle.util.encoders.Hex.toHexString(hmacMD5));    }

 

Java加密算法