1. md5加密,常用于加密用户名密码,当用户验证时。
protected byte[] encrypt(byte[] obj) ...{
try ...{
messagedigest md5 = messagedigest.getinstance("md5");
md5.update(obj);
return md5.digest();
} catch (nosuchalgorithmexception e) ...{
e.printstacktrace();
}
}
|
2. sha加密,与md5相似的用法,只是两者的算法不同。
protected byte[] encrypt(byte[] obj) ...{
try ...{
messagedigest sha = messagedigest.getinstance("sha");
sha.update(obj);
return sha.digest();
} catch (nosuchalgorithmexception e) ...{
e.printstacktrace();
}
}
|
3. rsa加密,ras加密允许解密。常用于文本内容的加密。
import java.security.keypair;
import java.security.keypairgenerator;
import java.security.interfaces.rsaprivatekey;
import java.security.interfaces.rsapublickey;
import javax.crypto.cipher;
/** *//**
* <b>rsaencrypt</b>
* <p>
* @author maqujun
* @see
*/
public class rsaencrypt ...{
/** *//**
* main method for rsaencrypt.
* @param args
*/
public static void main(string[] args) ...{
try ...{
rsaencrypt encrypt = new rsaencrypt();
string encrypttext = "encrypttext";
keypairgenerator keypairgen = keypairgenerator.getinstance("rsa");
keypairgen.initialize(1024);
keypair keypair = keypairgen.generatekeypair();
// generate keys
rsaprivatekey privatekey = (rsaprivatekey) keypair.getprivate();
rsapublickey publickey = (rsapublickey) keypair.getpublic();
byte[] e = encrypt.encrypt(publickey, encrypttext.getbytes());
byte[] de = encrypt.decrypt(privatekey,e);
system.out.println(encrypt.bytestostring(e));
system.out.println(encrypt.bytestostring(de));
} catch (exception e) ...{
e.printstacktrace();
}
}
/** *//**
* change byte array to string.
* @return byte[]
*/
protected string bytestostring(byte[] encrytpbyte) ...{
string result = "";
for (byte bytes : encrytpbyte) ...{
result += (char) bytes.intvalue();
}
return result;
}
/** *//**
* encrypt string.
* @return byte[]
*/
protected byte[] encrypt(rsapublickey publickey, byte[] obj) ...{
if (publickey != null) ...{
try ...{
cipher cipher = cipher.getinstance("rsa");
cipher.init(cipher.encrypt_mode, publickey);
return cipher.dofinal(obj);
} catch (exception e) ...{
e.printstacktrace();
}
}
return null;
}
/** *//**
* basic decrypt method
* @return byte[]
*/
protected byte[] decrypt(rsaprivatekey privatekey, byte[] obj) ...{
if (privatekey != null) ...{
try ...{
cipher cipher = cipher.getinstance("rsa");
cipher.init(cipher.decrypt_mode, privatekey);
return cipher.dofinal(obj);
} catch (exception e) ...{
e.printstacktrace();
}
}
return null;
}
}
|