MD加密常用于加密用户名密码当用户验证时
protected byte[] encrypt(byte[] obj) { try { MessageDigest md = MessageDigestgetInstance(MD); mdupdate(obj); return mddigest(); } catch (NoSuchAlgorithmException e) { eprintStackTrace(); } }
SHA加密与MD相似的用法只是两者的算法不同
protected byte[] encrypt(byte[] obj) { try { MessageDigest sha = MessageDigestgetInstance(SHA); shaupdate(obj); return shadigest(); } catch (NoSuchAlgorithmException e) { eprintStackTrace(); } }
RSA加密RAS加密允许解密常用于文本内容的加密
import javasecurityKeyPair; import javasecurityKeyPairGenerator; import javasecurityinterfacesRSAPrivateKey; import javasecurityinterfacesRSAPublicKey; import javaxcryptoCipher;/** *//** * RSAEncrypt * * @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 = KeyPairGeneratorgetInstance(RSA); keyPairGeninitialize(); KeyPair keyPair = keyPairGengenerateKeyPair(); // Generate keys RSAPrivateKey privateKey = (RSAPrivateKey) keyPairgetPrivate(); RSAPublicKey publicKey = (RSAPublicKey) keyPairgetPublic(); byte[] e = encryptencrypt(publicKey encryptTextgetBytes()); byte[] de = encryptdecrypt(privateKeye); Systemoutprintln(encryptbytesToString(e)); Systemoutprintln(encryptbytesToString(de)); } catch (Exception e) { eprintStackTrace(); } } /** *//** * Change byte array to String * @return byte[] */ protected String bytesToString(byte[] encrytpByte) { String result = ; for (Byte bytes : encrytpByte) { result += (char) bytesintValue(); } return result; } /** *//** * Encrypt String * @return byte[] */ protected byte[] encrypt(RSAPublicKey publicKey byte[] obj) { if (publicKey != null) { try { Cipher cipher = CiphergetInstance(RSA); cipherinit(CipherENCRYPT_MODE publicKey); return cipherdoFinal(obj); } catch (Exception e) { eprintStackTrace(); } } return null; } /** *//** * Basic decrypt method * @return byte[] */ protected byte[] decrypt(RSAPrivateKey privateKey byte[] obj) { if (privateKey != null) { try { Cipher cipher = CiphergetInstance(RSA); cipherinit(CipherDECRYPT_MODE privateKey); return cipherdoFinal(obj); } catch (Exception e) { eprintStackTrace(); } } return null; } }