Delphi异或算法转换为java实现
#Delphi运算符转JAVA#【转AscII码】ord()→int(char);【右移】shr→>>;【左移】shl→<<;【自增】inc(i)→i++
一、Delphi异或算法实现
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
function YiHuoEncrypt(Str:String):String;//字符加密函數 這是用的一個異或加密 var i,j:Integer; const xKey :array[0..7] of Byte=($AA,$BB,$CC,$DD,$EE,$FF,$AB,$CD); //字符串加密用 查询传输 begin Result:=''; j:=0; for i:=1 to Length(Str) do begin Result:=Result+IntToHex((Byte(Str[i]) xor XKey[j]),2); j:=(j+1) mod 8; end; end;
转换为Java的异或算法实现:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public static String EncrySck(String s){ byte xKey[] = {Byte.parseByte( "0xAA" ),Byte.parseByte("0xBB" ),Byte.parseByte("0xCC" ),Byte.parseByte("0xDD" ),Byte.parseByte("0xFF" ),Byte.parseByte("0xAB" ),Byte.parseByte("0xCD" ),Byte.parseByte("0xEF" )}; String result = ""; int j = 0; int a = 0; byte[] data = s.getBytes(); for(int i = 0;i<s.length();i++){ a = (data[i] ^ xKey[j]); result = result + Integer.toHexString(a); j = (j+1)% 8; } return result; }
二、Delphi的Encode7bit算法实现:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
function Encode7bit(src:string):string; var i,j,cur,len:integer; t:string; begin i := 1; j := 0; result:=''; len:=length(src); while(i<=len) do begin if (i<len) then cur:=(ord(src[i]) shr j) or ((ord(src[i+1]) shl (7-j)) and $FF) else // 最后一位 cur:=(ord(src[i]) shr j) and $7F; t:=inttohex(cur,2); result:=result+t; inc(i); j:=(j+1) mod 7; if j=0 then inc(i); end; end;
转换为Java的Encode7bit算法实现:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
/* * 加密前:1234567890 * 加密后: 31D98C56B3DD703918 * */ private String Encode7bit(String src){ String result = null; System.out.println("before:"+src); int i=0,j=0,cur,len; String t; len = src.length(); char[] srcarr = src.toCharArray(); while(i<len){ if (i<len-1) { cur=(char2AscII(srcarr[i]) >> j) | ((char2AscII(srcarr[i+1]) << (7-j)) & 255); }else {// 最后一位 cur=(char2AscII(srcarr[i]) >> j) & 127; } t=toHexStr(cur); System.out.println("j:"+j+"__srcarr[i="+i+"]:"+srcarr[i]+"__cur:"+cur+"__t:"+t); result=result+t; i++; j=(j+1) % 7; if (j==0) i++; } System.out.println("result:"+result.toUpperCase()); return result.toUpperCase(); } /* * int转换成两位16进制数 */ private String toHexStr(int cur){ String result = Integer.toHexString(cur); if(result.length()<2){ result = "0" + result; } return result; } /* * 字符转AscII码 */ private static int char2AscII(char a){ return (int) a; } /* * 字符串转换为ASCII码 */ public static int[] string2ASCII(String s) { if (s == null || "".equals(s)) { return null; } char[] chars = s.toCharArray(); int[] asciiArray = new int[chars.length]; for (int i = 0; i < chars.length; i++) { asciiArray[i] = char2AscII(chars[i]); } return asciiArray; }