java字符串解码处理

 无正道 发布于 2022-11-02 08:25

java处理一个用delphi语言加了密的字符串,可获得对应的ascii数值,如果一般的英文通过(char)x的方式就能转换成对应的英文字符,但是对于中文,会有2个对应的数值,这个怎么拼装能还原为对应的中文?源码如下:

//*******************************************************************
加密字符串为:15ffac3e55,解码后正确的结果应该是“A胡”
//*******************************************************************

//示例
AJ2013XorEnDecode tt = new XorEnDecode();
System.out.println(tt.xorDecode("TEV3_TJGLXT.2013", "15ffac3e55"));

//解密类的源码***************************************************************************

public class XorEnDecode {  
   private int StrToIntDef(String str,int defaultint){      
     try { 
          return Integer.parseInt(str,16);
          } 
     catch (Exception e) {
          return defaultint;
         }
   }




public String xorDecode(String Key, String Source){
        //解密Express     
        char C;
        String Result="";

    for (int i = 0; i < Math.floor(Source.length()/2)-1; i++) {
       C = (char)StrToIntDef(Source.substring((i * 2) , (i * 2) + 2),32);               

       if (Key.length() > 0) {
         C = (char)((int)Key.charAt((i % Key.length())) ^ (int)C)  ;                    
       }            
       Result = Result + C;         
    }
    return Result;
}

}

其实问题就出在 Result = Result + C; 这个连接的C值上,对应英文这样连接OK的,对于中文就有问题了。

在delphi里这个C值如果不是个正常的字符,用chr()进行转换,它会保留原先的ascii的值,直接参与后面的连接,通过2次单字节的连接后,就能转换成对应的中文。 但在java里单字节C值就会转换成特殊字符,所以就变成乱码。 刚刚接触JAVA,不知道如何破。

1 个回答
  • Java的字符串相加就是真的字符串相加,它不是字节码组合,所以你需要先解密成字节码最后转换成字符串。
    代码:

        public String xorDecode(String Key, String Source) {
            // 解密Express
            int C;
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
    
            for (int i = 0; i < Math.floor(Source.length() / 2) - 1; i++) {
                C = StrToIntDef(Source.substring((i * 2), (i * 2) + 2), 32);
    
                if (Key.length() > 0) {
                    C = (int) Key.charAt((i % Key.length())) ^ (int) C;
                }
                bos.write(C);
            }
            try {
                return new String(bos.toByteArray(), "GBK");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return null;
            }
        }
    

    输出:A胡

    2022-11-04 04:35 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有