這裏使用到了getBytes() 將位數組轉爲String類型
public static String encrypt(String value,char secret){
//字符串轉byte數組
byte[] bt=value.getBytes();
//進行遍歷加密
for(int i=0;i<bt.length;i++)
bt[i]=(byte)(bt[i]^(int)secret); //進行異或運算
//將位數組轉爲String類型
String newresult=new String(bt,0,bt.length);
return newresult; //返回String類型
}
public static void main(String[] args) {
String str="hello,world";
String str1 = encrypt(str,'8');
System.out.println("加密後:"+str1);
str1 = encrypt(str1,'8'); //重新進行異或就可以解密了
System.out.println("解密後:"+str1);
}
運行結果:
加密後:P]TTWOWJT
解密後:hello,world