篇三:Java加密

一、加密基础知识

  加密大体上可以分为“双向加密”和“单向加密”,双向加密又分为“对称加密”和“非对称加密”;

  双向加密:通过算法将明文加密后形成密文,可以通过算法还原密文;

  单向加密:对消息进行摘要计算,并不能通过算法还原密文;

       常用单向加密:MD5、SHA

  对称加密:同一个密钥(算法)可以同时用作消息的加密和解密,也称单密钥加密。

       常用的对称加密:DES、IDEA、RC2、RC4、SKIPJACK、RC5、AES

  非对称加密:存在公钥、私钥,公钥加密需私钥解密,私钥加密需公钥解密

        常用的非对称加密:RSA、DSA

 

二、加密的实现

 学习地址:http://zhangyiqian.iteye.com/blog/1470713

 1、单向加密的实现:MD5/SHA

  a、MessageDigest工厂类

   学习地址:http://blog.csdn.net/hudashi/article/details/8394158

        http://blog.csdn.net/ma1kong/article/details/2662997

   MessageDigest 类为应用程序提供信息摘要算法的功能,如 MD5 或 SHA 算法。信息摘要是安全的单向哈希函数,它接收任意大小的数据,并输出固定长度的哈希值。

  常用步骤:

1、getInstance() 初始化 MessageDigest对象,工厂类,不能new对象;
2、update()方法处理数据,在digest()方法前任何时候都可以调用reset()方法重新处理数据;
3、digest()方法执行,获取哈希值;
4、数组转换成String字符串

  具体代码:java.security.MessageDigest

MessageDigest m=MessageDigest.getInstance("MD5");
//MessageDigest m=MessageDigest.getInstance("SHA");

//初始化值,也可以直接 m.digest(byte[] byte)
m.update(str.getBytes("UTF-8" ));

//计算消息摘要
byte s[ ]=m.digest( );

//处理计算结果
StringBuffer strBuffer = new StringBuffer();
for (int i = 0; i < s.length; i++) {
   strBuffer.append(Integer.toHexString(s[i]));
}
String mess = strBuffer.toString();

  b、commons-codec包

//MD5加密
DigestUtils.md5Hex(str);

//SHA 加密
DigestUtils.shaHex(str);

 

 2、对称、非对称加密实现:AES、DES、RSA

  javax.crypto包

  对称加密

package java_crypto_symmetric;  
  
import java.security.InvalidKeyException;    
import java.security.NoSuchAlgorithmException;    
//import java.security.Security;    
    
import javax.crypto.BadPaddingException;    
import javax.crypto.Cipher;    
import javax.crypto.IllegalBlockSizeException;    
import javax.crypto.KeyGenerator;    
import javax.crypto.NoSuchPaddingException;    
import javax.crypto.SecretKey;    
    
public class AESdemo {    
        
    //KeyGenerator 提供对称密钥生成器的功能,支持各种算法    
    private KeyGenerator keygen;    
    //SecretKey 负责保存对称密钥    
    private SecretKey deskey;    
    //Cipher负责完成加密或解密工作    
    private Cipher c;    
    //该字节数组负责保存加密的结果    
    private byte[] cipherByte;    
        
    public AESdemo() throws NoSuchAlgorithmException, NoSuchPaddingException{    
//        Security.addProvider(new com.sun.crypto.provider.SunJCE());    
        //实例化支持DES算法的密钥生成器(算法名称命名需按规定,否则抛出异常)    
        keygen = KeyGenerator.getInstance("AES");    
        //生成密钥    
        deskey = keygen.generateKey();    
        //生成Cipher对象,指定其支持的DES算法    
        c = Cipher.getInstance("AES");    
    }    
        
    /**  
     * 对字符串加密  
     *   
     * @param str  
     * @return  
     * @throws InvalidKeyException  
     * @throws IllegalBlockSizeException  
     * @throws BadPaddingException  
     */    
    public byte[] Encrytor(String str) throws InvalidKeyException,    
            IllegalBlockSizeException, BadPaddingException {    
        // 根据密钥,对Cipher对象进行初始化,ENCRYPT_MODE表示加密模式    
        c.init(Cipher.ENCRYPT_MODE, deskey);    
        byte[] src = str.getBytes();    
        // 加密,结果保存进cipherByte    
        cipherByte = c.doFinal(src);    
        return cipherByte;    
    }    
    
    /**  
     * 对字符串解密  
     *   
     * @param buff  
     * @return  
     * @throws InvalidKeyException  
     * @throws IllegalBlockSizeException  
     * @throws BadPaddingException  
     */    
    public byte[] Decryptor(byte[] buff) throws InvalidKeyException,    
            IllegalBlockSizeException, BadPaddingException {    
        // 根据密钥,对Cipher对象进行初始化,DECRYPT_MODE表示加密模式    
        c.init(Cipher.DECRYPT_MODE, deskey);    
        cipherByte = c.doFinal(buff);    
        return cipherByte;    
    }    
    
    /**  
     * @param args  
     * @throws NoSuchPaddingException   
     * @throws NoSuchAlgorithmException   
     * @throws BadPaddingException   
     * @throws IllegalBlockSizeException   
     * @throws InvalidKeyException   
     */    
    public static void main(String[] args) throws Exception {    
        AESdemo de1 = new AESdemo();    
        String msg ="www.suning.com/index.jsp";    
        byte[] encontent = de1.Encrytor(msg);    
        byte[] decontent = de1.Decryptor(encontent);    
        System.out.println("明文是:" + msg);    
        System.out.println("加密后:" + new String(encontent));    
        System.out.println("解密后:" + new String(decontent));    
    }    
    
}  

  非对称加密

package java_crypto_asymmetric;  
  
import java.security.InvalidKeyException;  
import java.security.KeyPair;  
import java.security.KeyPairGenerator;  
import java.security.NoSuchAlgorithmException;  
import java.security.interfaces.RSAPrivateKey;  
import java.security.interfaces.RSAPublicKey;  
  
import javax.crypto.BadPaddingException;  
import javax.crypto.Cipher;  
import javax.crypto.IllegalBlockSizeException;  
import javax.crypto.NoSuchPaddingException;  
  
public class RSAdemo {  
  
    /** 
     * 加密 
     *  
     * @param publicKey 
     * @param srcBytes 
     * @return 
     * @throws NoSuchAlgorithmException 
     * @throws NoSuchPaddingException 
     * @throws InvalidKeyException 
     * @throws IllegalBlockSizeException 
     * @throws BadPaddingException 
     */  
    protected byte[] encrypt(RSAPublicKey publicKey, byte[] srcBytes) throws NoSuchAlgorithmException,  
            NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {  
        if (publicKey != null) {  
            // Cipher负责完成加密或解密工作,基于RSA  
            Cipher cipher = Cipher.getInstance("RSA");  
            // 根据公钥,对Cipher对象进行初始化  
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);  
            byte[] resultBytes = cipher.doFinal(srcBytes);  
            return resultBytes;  
        }  
        return null;  
    }  
  
    /** 
     * 解密 
     *  
     * @param privateKey 
     * @param srcBytes 
     * @return 
     * @throws NoSuchAlgorithmException 
     * @throws NoSuchPaddingException 
     * @throws InvalidKeyException 
     * @throws IllegalBlockSizeException 
     * @throws BadPaddingException 
     */  
    protected byte[] decrypt(RSAPrivateKey privateKey, byte[] srcBytes) throws NoSuchAlgorithmException,  
            NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {  
        if (privateKey != null) {  
            // Cipher负责完成加密或解密工作,基于RSA  
            Cipher cipher = Cipher.getInstance("RSA");  
            // 根据公钥,对Cipher对象进行初始化  
            cipher.init(Cipher.DECRYPT_MODE, privateKey);  
            byte[] resultBytes = cipher.doFinal(srcBytes);  
            return resultBytes;  
        }  
        return null;  
    }  
  
    /** 
     * @param args 
     * @throws NoSuchAlgorithmException 
     * @throws BadPaddingException 
     * @throws IllegalBlockSizeException 
     * @throws NoSuchPaddingException 
     * @throws InvalidKeyException 
     */  
    public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException,  
            IllegalBlockSizeException, BadPaddingException {  
        RSAdemo rsa = new RSAdemo();  
        String msg = "www.suning.com/index.jsp";  
        // KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象  
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");  
        // 初始化密钥对生成器,密钥大小为1024位  
        keyPairGen.initialize(1024);  
        // 生成一个密钥对,保存在keyPair中  
        KeyPair keyPair = keyPairGen.generateKeyPair();  
        // 得到私钥  
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();  
        // 得到公钥  
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();  
  
        // 用公钥加密  
        byte[] srcBytes = msg.getBytes();  
        byte[] resultBytes = rsa.encrypt(publicKey, srcBytes);  
  
        // 用私钥解密  
        byte[] decBytes = rsa.decrypt(privateKey, resultBytes);  
  
        System.out.println("明文是:" + msg);  
        System.out.println("加密后是:" + new String(resultBytes));  
        System.out.println("解密后是:" + new String(decBytes));  
    }  
  
} 

   Base64加密

//加密
<!---->String str= "abc"; // abc为要加密的字符串
byte[] b = Base64.encodeBase64(str.getBytes(), true);
System.out.println(new String(b));
//解密
<!---->String str = "YWJj"; // YWJj为要解密的字符串
byte[] b = Base64.decodeBase64(str.getBytes());
System.out.println(new String(b));
import org.apache.commons.codec.binary.Base64;

public class test {
    public static void main(String[] args) {
        Base64 b64 = new Base64();
        String message = "测试Base64加密";
        String enc = new String(b64.encode(message.getBytes()));
        System.out.println(enc);
        System.out.println(new String(b64.decode(enc)));
    }
}
public class Base64 {

    private static char[] base64EncodeChars = new char[] { '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', '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 };

    private Base64(){
    }

    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();
    }

    public static byte[] decode(String str){
        byte[] data = str.getBytes();
        int len = data.length;
        ByteArrayOutputStream buf = new ByteArrayOutputStream(len);
        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;
            }
            buf.write(((b1 << 2) | ((b2 & 0x30) >>> 4)));

            /* b3 */
            do {
                b3 = data[i++];
                if (b3 == 61) {
                    return buf.toByteArray();
                }
                b3 = base64DecodeChars[b3];
            } while (i < len && b3 == -1);
            if (b3 == -1) {
                break;
            }
            buf.write((((b2 & 0x0f) << 4) | ((b3 & 0x3c) >>> 2)));

            /* b4 */
            do {
                b4 = data[i++];
                if (b4 == 61) {
                    return buf.toByteArray();
                }
                b4 = base64DecodeChars[b4];
            } while (i < len && b4 == -1);
            if (b4 == -1) {
                break;
            }
            buf.write((((b3 & 0x03) << 6) | b4));
        }
        return buf.toByteArray();
    }
    
    public static void main(String[] args) {
        String message = "Base64加密测试";
        String tt = encode(message.getBytes());
        System.out.println(encode(message.getBytes()));
        System.out.println(new String(decode(tt)));
        
        
        String ec = new String(org.apache.commons.codec.binary.Base64.encodeBase64(message.getBytes(),true));
        System.out.println(ec);
        System.out.println(new String(org.apache.commons.codec.binary.Base64.decodeBase64(ec)));
    }
}

 

  

 

    

 

posted @ 2016-12-05 21:26  刘广平  阅读(217)  评论(0)    收藏  举报