java aes 求助啊

好为 发布于 2013/08/29 20:54
阅读 260
收藏 0
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import it.sauronsoftware.base64.*;

public class test {
	
	 public static void main(String[] args) throws Exception {
	        String cKey = "1234567890123456";
	        String cSrc = "123456781234567890";
	        System.out.println(cSrc);
	        String enString = encrypt(cSrc, cKey);
	        System.out.println("加密后的字串是:" + enString);
	        String DeString = decrypt(enString, cKey);
	        System.out.println("解密后的字串是:" + DeString);
	    }
	
    public static String encrypt(String sSrc, String sKey) throws Exception {
        if (sKey == null) {
            System.out.print("Key为空null");
            return null;
        }
        if (sKey.length() != 16) {
            System.out.print("Key长度不是16位");
            return null;
        }
        byte[] raw = sKey.getBytes("utf-8");
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));

        return Base64.encode(new String(encrypted));
    }

    public static String decrypt(String sSrc, String sKey) throws Exception {
        try {
            if (sKey == null) {
                System.out.print("Key为空null");
                return null;
            }
            if (sKey.length() != 16) {
                System.out.print("Key长度不是16位");
                return null;
            }
            byte[] raw = sKey.getBytes("utf-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            byte[] encrypted1 = Base64.decode(sSrc).getBytes("utf-8");
            try {
                byte[] original = cipher.doFinal(encrypted1);
                String originalString = new String(original,"utf-8");
                return originalString;
            } catch (Exception e) {
                System.out.println(e.toString());
                return null;
            }
        } catch (Exception ex) {
            System.out.println(ex.toString());
            return null;
        }
    }
}
加载中
0
好为
好为
@红薯 帮忙看看啊
0
苗哥
苗哥
这个只有壹串代码,但是不知道你想问什么……
好为
好为
这个配发截图了
0
vidy_tu
vidy_tu

你打个断点看下30行的和49行的encrypted是不是一样的,估计是转成String后byte[] 丢失了,位数不是16的倍数了. 

好为
好为
我都快被搞死了
返回顶部
顶部