import java.io.ByteArrayOutputStream; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; public class Main { public static void main(String[] args) { String s = new String("2342356`中户人民@¥#%&*()-=|+_}{[]/.,;:,.>》》"); String enc = encrypt(s, "f8ee541137a2aa381abaac17886653ba"); System.out.println("加密的:" + enc); } private static String convert(String inStr, String secretKey) { char[] a = inStr.toCharArray(); char[] s = rmRepeated(secretKey).toCharArray(); for (int i = 0; i<s.length; i++) { for (int j = 0; j <a.length; j++) { a[j] = (char) (a[j] ^ s[i]); } } String r = new String(a); return r; } private static String rmRepeated(String s) { int len = s.length(); int k = 0; int count = 0; String str = ""; char[] c = new char[len]; for (int i = 0; i<len; i++) { c[i] = s.charAt(i); } for (int i = 0; i<len; i++) { k = i + 1; while (k <len - count) { if (c[i] == c[k]) { for (int j = k; j <len - 1; j++) { c[j] = c[j + 1];// 出现重复字母,从k位置开始将数组往前挪位 } count++;// 重复字母出现的次数 k--; } k++; } } for (int i = 0; i<len - count; i++) { str += String.valueOf(c[i]); } return str; } private static String hexString= "0123456789ABCDEF"; public static String encode(String str) { // 根据默认编码获取字节数组 String r=""; try { byte[] bytes = str.getBytes("UTF-8"); StringBuilder sb = new StringBuilder(bytes.length* 2); // 将字节数组中每个字节拆解成2位16进制整数 for (int i = 0; i<bytes.length; i++) { sb.append(hexString.charAt((bytes[i] &0xf0) >>4)); sb.append(hexString.charAt((bytes[i] &0x0f) >>0)); } r=sb.toString(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return r; } public static String encrypt(String inStr, String secretKey) { String hexStr=convert(inStr, secretKey); return encode(hexStr); } }
我寫的php
public function encrypt(){ return bin2hex($this->convert1('2342356`中户人民@¥#%&*()-=|+_}{[]/.,;:,.>》》','f8ee541137a2aa381abaac17886653ba')); } public function convert($str,$app_key){ $a = str_split($str); $s = str_split(implode(array_unique(str_split($app_key)))); for ($i = 0; $i<count($s); $i++) { for ($j = 0; $j <count($a); $j++) { $a[$j] = $a[$j]^$s[$i]; } } return implode($a); }
這兩者回傳的加密內容不一致 好像是中文異或的問題