java 利用异或^进行加密

package com.zcj.eg001;

import java.nio.charset.Charset;

import org.junit.Test;


public class Encryption {
    public static void main(String[] args) {
        String pwd = "123456test";
        //简易版
        test1(pwd);
        //复杂版
        System.out.println();
        test2(pwd);
    }
    
    
    public static void test1(String pwd) {
        char[] cs = pwd.toCharArray();
        for(int i = 0;i<cs.length;i++) {
            cs[i] = (char)(cs[i]^20000);
            
        }
        
        String encode = new String(cs);
        System.out.println("加密后:"+encode);
        
        char[] css = new String(cs).toCharArray();
        for(int i = 0;i<css.length;i++) {
            css[i] = (char)(css[i]^20000);
        }
        
        String decode = new String(css);
        System.out.println("解密后:"+decode);
        
    }
     
    
    public static void test2(String pwd) {  
        String enc = encode(pwd);  
        System.out.println("加密后:"+enc);  
        String dec = decode(enc);  
        System.out.println("解密后:"+dec);  
    } 
    
    private static final String key0 = "FECddfOI()*&<MNCXZPKL";  
    private static final Charset charset = Charset.forName("UTF-8");  
    private static byte[] keyBytes = key0.getBytes(charset);  
      
    public static String encode(String enc){  
        byte[] b = enc.getBytes(charset);  
        for(int i=0,size=b.length;i<size;i++){  
            for(byte keyBytes0:keyBytes){  
                b[i] = (byte) (b[i]^keyBytes0);  
            }  
        }  
        return new String(b);  
    }  
      
    public static String decode(String dec){  
        byte[] e = dec.getBytes(charset);  
        byte[] dee = e;  
        for(int i=0,size=e.length;i<size;i++){  
            for(byte keyBytes0:keyBytes){  
                e[i] = (byte) (dee[i]^keyBytes0);  
            }  
        }  
        return new String(e);  
    }  
  
   

}

运行后结果如下:

加密后:丑丒专且丕世乔久乓乔
解密后:123456test

加密后:567012pawp
解密后:123456test

posted @ 2018-07-18 16:01  真某人  阅读(2727)  评论(0编辑  收藏  举报