English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Example code of simple encryption and decryption algorithm using XOR operation in Java

A simple encryption and decryption algorithm using XOR operation

Example1:

package cn.std.util;
import java.nio.charset.Charset;
public class DeEnCode {
	private static final String key0 = "FECOI()";*&<MNCXZPKL";
	private static final Charset charset = Charset.forName("UTF-8");-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);
	}
	public static void main(String[] args) {
		String s="you are right";
		String enc = encode(s);
		String dec = decode(enc);
		System.out.println(enc);
		System.out.println(dec);
	}
}

Example2

public static String setEncrypt(String str){
	String sn="ziyu";
	//Key
	int[] snNum=new int[str.length()];
	String result="";
	String temp="";
	for (int i=0,j=0;i<str.length();i++,j++{
		if(j==sn.length())
		        j=0;
		snNum[i]=str.charAt(i)^sn.charAt(j);
	}
	for (int k=0;k<str.length();k++{
		if(snNum[k]<10{
			temp="00"+snNum[k];
		}
			if(snNum[k]<100){
				temp="0"+snNum[k];
			}
		}
		result+=temp;
	}
	return result;
}
public static String getEncrypt(String str){
	String sn="ziyu";
	//Key
	char[] snNum=new char[str.length()/3];
	String result="";
	for (int i=0,j=0;i<str.length()/3;i++,j++{
		if(j==sn.length())
		        j=0;
		int n=Integer.parseInt(str.substring(i*3,i*3+3));
		snNum[i]=(char)((char)n^sn.charAt(j));
	}
	for (int k=0;k<str.length()/3;k++{
		result+=snNum[k];
	}
	return result;
}
}

Summary

That's all about the example code of the simple encryption and decryption algorithm using XOR operation in Java. I hope it will be helpful to everyone. Those who are interested can continue to read other related topics on this site. Welcome to leave a message if there is anything insufficient. Thank you for your support to this site!

Statement: The content of this article is from the network, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been edited by humans, and does not assume any relevant legal responsibility. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email for reporting. Provide relevant evidence, and once verified, this site will immediately delete the suspected infringing content.)

You May Also Like