加密法(AES,MD5)----对String加密

来源:互联网 发布:最新的p2p网络投资 编辑:程序博客网 时间:2024/06/03 12:11

 对String的加密是在对byte[]的加密基础上进行的。

就是把String转回byte数组输入,然后在把byte数组转回String输出

 

加密:

 

private String getEncString(String msg) {

byte[] ming = null;

byte[] enc = null;

String mStr = "";

BASE64Encoder base64en = new BASE64Encoder();

try {

ming = msg.getBytes("UTF-8");

enc = this.getEncCode(ming);

mStr = base64en.encode(enc);

} catch (UnsupportedEncodingException e) {

e.printStackTrace();

} finally {

ming = null;

enc = null;

base64en = null;

}

return mStr;

}

 

 

解密:

 

private String getDecString(String msg) {

BASE64Decoder base64dc = new BASE64Decoder();

byte[] enc = null;

byte[] ming = null;

String decStr = "";

try {

enc = base64dc.decodeBuffer(msg);

ming = this.getDecCode(enc);

decStr = new String(ming, "UTF-8");

} catch (IOException e) {

e.printStackTrace();

} finally {

base64dc = null;

enc = null;

ming = null;

}

return decStr;

}

 
上面的方法在前一篇文章有写到。
 
 
MD5加密:
 
private  byte[] encryptMD5(String msg) {
MessageDigest md5 = null;
try {
md5 = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
byte[] src = msg.getBytes();
md5.update(src);
byte[] result = md5.digest();
return result;
}
 
使用MD5的digest方法加密返回一个byte[]数组,再转回想要的类型。
 
 
在这两个加密法里面注意的是
 
要声明用的是哪种加密法如MD5:MessageDigest.getInstance("MD5");
AES:c = Cipher.getInstance("AES");
 
如果有什么不对的地方,大家也可以指出来大家一起学习。
 

本文出自 “Just do it” 博客,请务必保留此出处http://davenzeng.blog.51cto.com/3896952/989640

0 0
原创粉丝点击