This article mainly introduces the RC4 encryption and decryption algorithm implemented in java, and analyzes the implementation and usage skills of the java RC4 encryption and decryption algorithm in the form of specific examples. Friends in need can refer to the following
The examples in this article describe RC4 encryption and decryption algorithm implemented in java. Share it with everyone for your reference. The details are as follows:
There is a project that needs to parse an rc4 encrypted file provided by a user. I specially searched and compiled a Java version of the RC4 encryption and decryption algorithm. .
public static String HloveyRC4(String aInput,String aKey) { int[] iS = new int[256]; byte[] iK = new byte[256]; for (int i=0;i<256;i++) iS[i]=i; int j = 1; for (short i= 0;i<256;i++) { iK[i]=(byte)aKey.charAt((i % aKey.length())); } j=0; for (int i=0;i<255;i++) { j=(j+iS[i]+iK[i]) % 256; int temp = iS[i]; iS[i]=iS[j]; iS[j]=temp; } int i=0; j=0; char[] iInputChar = aInput.toCharArray(); char[] iOutputChar = new char[iInputChar.length]; for(short x = 0;x<iInputChar.length;x++) { i = (i+1) % 256; j = (j+iS[i]) % 256; int temp = iS[i]; iS[i]=iS[j]; iS[j]=temp; int t = (iS[i]+(iS[j] % 256)) % 256; int iY = iS[t]; char iCY = (char)iY; iOutputChar[x] =(char)( iInputChar[x] ^ iCY) ; } return new String(iOutputChar); }
Use this method for both encryption and decryption. In other words, the parameter String aInput can be passed in plain text or an encrypted string, and the program will automatically recognize it. Then perform encrypted and decrypted response operations.
Usage examples are as follows:
public static void main(String[] args) { String inputStr = "做个好男人"; String key = "abcdefg"; String str = HloveyRC4(inputStr,key); //打印加密后的字符串 System.out.println(str); //打印解密后的字符串 System.out.println(HloveyRC4(str,key)); }
The above is the detailed content of Example tutorial of implementing RC4 encryption and decryption in java. For more information, please follow other related articles on the PHP Chinese website!