In our program design, we often want to encrypt some special content, today summed up a few simple encryption methods, share to everyone!
How to use Java implementation string simple encryption decryption? In order to ensure the security of users ' information, the system must save the user's password to the database.
When you need to use the password, take out the data, decrypt the processing.
Avoid saving plaintext passwords.
Programme I:
Package com.tnt.util;
Import Java.security.MessageDigest; public class Stringutil {private final static string[] hexdigits = {"0", "1", "2", "3", "4", "5", "6", "7",
"8", "9", "a", "B", "C", "D", "E", "F"}; /** * Convert byte array to 16 String * * @param b * byte array * @return 16-string/public static string by
Tearraytohexstring (byte[] b) {StringBuffer RESULTSB = new StringBuffer ();
for (int i = 0; i < b.length i++) {resultsb.append (bytetohexstring (b[i));
return resultsb.tostring ();
private static String bytetohexstring (byte b) {int n = b;
if (n < 0) n = 256 + N;
int D1 = N/16;
int d2 = n% 16;
return HEXDIGITS[D1] + HEXDIGITS[D2];
public static string Md5encode (String origin) {string resultstring = null;
try {resultstring = new String (origin);
MessageDigest MD = messagedigest.getinstance ("MD5"); resultstring = bytearraytohexstring (Md.digest (resultstring. GetBytes ()));
The catch (Exception ex) {} return resultstring;
public static void Main (string[] args) {System.err.println (Md5encode ("123456"));
}
}
Scenario Two
Package com.shangyu.core.utils;
public class MD5 {public static String getMD5 (byte[] Source {string s = null; Char hexdigits[] = {//The character ' 0 ' that is used to convert bytes into a 16-binary notation ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 ', ' A ', ' B ', ' C ', ' d ', ' e ', ', '
F '};
try {java.security.MessageDigest MD = java.security.MessageDigest. getinstance ("MD5");
Md.update (source); byte tmp[] = Md.digest (); The result of the MD5 is a 128-bit long integer,//The byte representation is 16 bytes char str[] = new char[16 * 2]; Each byte is expressed in 16, using two characters,//So the expression of 16 binary requires 32 characters int k = 0; Represents the corresponding character position in the transformation result for (int i = 0; i < i++) {//conversion byte BYTE0 = Tmp[i] For each byte of MD5//converted to 16 character from the first byte; Take the first byte str[k++] = Hexdigits[byte0 >>> 4 & 0xf]; In bytes high 4 digit conversion,//>>>/For logical right SHIFT, move symbol bit right together str[k++] = hexdigits[byte0 & 0xf]; A numeric conversion of low 4 digits in byte = new String (str);
The result converted to string} catch (Exception e) {e.printstacktrace ();
return s; public static string getMD5 (String str) {return getMD5 (str.geTbytes ());
public static void Main (string[] args) {System.out.println (Md5.getmd5 ("123456"));
}
}
Thank you for reading, I hope to help you, thank you for your support for this site!