package com.cnd3b.utility;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.security.MessageDigest;

public class Encryption {
    /**
     * MD5¼ÓÃÜ
     *
     * @param str
     * @return
     */
    public String Encode_MD5(String str) {
        StringBuffer buf = new StringBuffer();
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(str.getBytes());
            byte b[] = md.digest();
            int i;
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0) {
                    i += 256;
                }
                if (i < 16) {
                    buf.append("0");
                }
                buf.append(Integer.toHexString(i));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return buf.toString();
    }


    /**
     * Base64¼ÓÃÜ
     *
     * @param str
     * @return
     */
    public String Encode_Base64(String str) {
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(str.getBytes());
    }

    /**
     * Base64½âÃÜ
     *
     * @param str
     * @return
     */
    public String Decode_Base64(String str) throws Exception {
        BASE64Decoder decoder = new BASE64Decoder();
        return new String(decoder.decodeBuffer(str));
    }

    public static void main(String[] args) {
        Encryption a = new Encryption();
        try {
            a.Encode_Base64("123456");
            a.Decode_Base64("MTIzNDU2Nw==");
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}
