Java AES和SHA示例

来源:互联网 发布:淘宝改评价 编辑:程序博客网 时间:2024/06/05 13:07

import java.security.Key;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class Test2 {

public static String sha1key = "00003ecea46d1111";//16位public static String aeskey = "000000007da2998caf4cf04d11111111";//32位/** * 128位AES加密 * @param key 密钥,16禁止表示的字符串,长度为32 * @param content 明文 * @return 密文 */public static String encryptByAES(String key, String content) {    if(key==null || content == null)return null;    byte[] keyBytes = hexString2Bytes(key);    try {        Key k = new SecretKeySpec(keyBytes, "AES");        Cipher cipher = Cipher.getInstance("AES");        cipher.init(Cipher.ENCRYPT_MODE, k);        byte[] output = cipher.doFinal(content.getBytes("UTF-8"));        return bytes2HEXString(output);    } catch(Exception e) {        System.out.println("AES加密失败");    }    return null;}public static void main(String[] args) {    String doTime = (new SimpleDateFormat("yyyyMMddHHmmss")).format(new Date());    System.out.println("time=" + doTime);    String content = "time="+doTime + "&mobile=13558696658";    System.out.println("content=" + content);    System.out.println("AES=" + encryptByAES(aeskey, content));    System.out.println("SHA=" + encryptBySHA(content + sha1key));}public static String encryptBySHA(String content) {    if(content == null) return null;    try {        MessageDigest md = MessageDigest.getInstance("SHA");        byte[] output = md.digest(content.getBytes("UTF-8"));        return bytes2HEXString(output);    }catch (Exception e) {        e.printStackTrace();    }    return null;}public static String bytes2HEXString(byte[] src) {    StringBuilder sb = new StringBuilder();    if(src==null || src.length<=0) {        return null;    }    for(int i=0; i<src.length; i++) {        int v = src[i]&0xFF;        String hv = Integer.toHexString(v);        if(hv.length() < 2) {            sb.append(0);        }        sb.append(hv);    }    return sb.toString();}public static byte[] hexString2Bytes(String hexString){    if(hexString =="" || hexString.equals("")){        return null;    }    hexString = hexString.toUpperCase();    int length = hexString.length() / 2;    char[] hexChars = hexString.toCharArray();    byte[] d = new byte[length];    for(int i= 0; i < length; i++){        int pos = i*2;        d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos+1]));    }    return d;}public static byte charToByte(char c){    return (byte) "0123456789ABCDEF".indexOf(c);}

}

0 0