By
Wind Vane
更新日期:
MD5
从给定字符串中提取32位字符串(只含16进制字符),输入与输出一一映射
JAVA
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * 返回字串的十六进制MD5编码格式字串 * @param str * @return */ public static String getMD5(String str){ char[] hexChar = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } md5.update(str.getBytes()); byte[] code = md5.digest(); // toHexString StringBuilder sb = new StringBuilder(code.length * 2); for (int i = 0; i < code.length; i++) { sb.append(hexChar[(code[i] & 0xf0) >>> 4]); sb.append(hexChar[code[i] & 0x0f]); } return sb.toString(); }
|
base64
将二进制编码映射为ASCII编码(占用空间会变大)
JAVA
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| import java.io.FileInputStream; import java.io.IOException;
import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder;
//从文件系统中读取文件,获取二进制流 public static byte[] getBytes( String uri ){ try { FileInputStream fis = new FileInputStream(uri); byte[] bytes = new byte[fis.available()]; fis.read(bytes); fis.close(); return bytes; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; }
public static String Encode( byte [] bytes ){ if (bytes == null) return ""; return new BASE64Encoder().encode(bytes); }
public static byte[] Decode( String str ){ byte[] bytes = null; BASE64Decoder decoder = new BASE64Decoder(); try { bytes = decoder.decodeBuffer(str); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return bytes; }
|
获取短字符串
将一个长字符串转为由新的一组字符组成的字符串,此处字符表包含数字和字母
原理:先从原字串提取32位MD5编码的字串,取其中12位转为一个16进制数,
每次取该数的低几位(不大于字母表的大小)作为字母表的索引,取该索引对应的值为结果的一个字符。
该方法的一个缺点是不能保证输入输出的一一映射。
JAVA
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| /** * 获取短字符串(极小可能出现重复结果) * @param str 要缩短的原字符串 * @return */ public static String getShortCode(String str){ str = GetMD5(str); char alphab[] = new char[62]; int j = 0; for (char i = '0'; i <= '9'; i++) alphab[j++] = i; for (char i = 'a'; i <= 'z'; i++) alphab[j++] = i; for (char i = 'A'; i <= 'Z'; i++) alphab[j++] = i; String part = ""; for (int i = 0; i < 24; i+=2) part += str.charAt(i); String res = ""; long hex = Long.parseLong(part, 16); while( hex > alphab.length - 1 ){ long index = alphab.length - 1 & hex; hex >>= 6; res += alphab[(int)index]; } return res; }
|