简单的位加密解密和MD5加密的例子

简单的位运算加密解密

package com.example.shoujiweishi.utils;

public class EncryptTools {
    
    /**
     * @param seed
     *      加密的种子
     * @param str
     *      要加密的字符串
     * @return
     */
    public static String encrypt(int seed,String str){
        byte[] bytes = str.getBytes();
        for (int i = 0; i < bytes.length; i++) {
            bytes[i] ^= seed;//对字节加密
        }
        return new String(bytes);
    }
    
    /**
     * @param seed
     *     解密的种子
     * @param str
     * @return
     */
    public static String decryption(int seed,String str){
        byte[] bytes = str.getBytes();
        for (int i = 0; i < bytes.length; i++) {
            bytes[i] ^= seed;//对字节加密
        }
        return new String(bytes);
    }

}

 

 

MD5加密,MD5加密不可逆

package com.example.shoujiweishi.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Md5Utils {
    public static String md5(String str){
        StringBuilder sb = new StringBuilder();
        try {
            //获取MD5加密器
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] bytes = str.getBytes();
            byte[] digest = md.digest(bytes);
            
            for (byte b : digest) {
                //把每个字节转换成16进制数
                int d = b & 0xff;//0x00 00 00 00 ff
                String hexString = Integer.toHexString(d);
                if(hexString.length() == 1){
                    hexString = "0" + hexString;
                }
                
                sb.append(hexString);
            }
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        return sb + "";
    }
}

 

posted @ 2016-03-15 20:12  znyyjk  阅读(925)  评论(0编辑  收藏  举报