流加密算法之Java RC4算法应用 附可用工具类

欢迎大家关注本博,同时欢迎大家评论交流,可以给个赞哦!!!

  RC4算法简介(来源于百度百科)

  RC4是密钥长度可变的流加密算法簇。RC4是一种在电子信息领域加密的技术手段,用于无线通信网络,是一种电子密码,只有经过授权(缴纳相应费用)的用户才能享受该服务。

  之所以称其为簇,是由于其核心部分的S-box长度可为任意,但一般为256字节。该算法的速度可以达到DES加密的10倍左右。

  RC4算法的原理很简单,包括初始化算法和伪随机子密码生成算法两大部分。假设S-box长度和密钥长度均为n。先来看看算法的初始化部分(用类C伪代码表示):

for (i=0; i<n; i++) {
    
    
	s[i]=i;
}
j=0;
for (i=0; i<n; i++) {
    
    
	j=(j+s[i]+k[i])%n;
	swap(s[i], s[j]);
}

  在初始化的过程中,密钥的主要功能是将S-box搅乱,i确保S-box的每个元素都得到处理,j保证S-box的搅乱是随机的。而不同的S-box在经过伪随机子密码生成算法的处理后可以得到不同的子密钥序列,并且,该序列是随机的:

i=j=0;
while (明文未结束) {
    
    
	++i%=n;
	j=(j+s)%n;
	swap(s, s[j]);
	sub_k=s((s+s[j])%n);
}

  得到的子密码sub_k用以和明文进行xor运算,得到密文,解密过程也完全相同。

  由于RC4算法加密是采用的xor,所以,一旦子密钥序列出现了重复,密文就有可能被破解。关于如何破解xor加密,请参看Bruce Schneier的Applied Cryptography一书的1.4节Simple XOR。那么,RC4算法生成的子密钥序列是否会出现重复呢?经过我的测试,存在部分弱密钥,使得子密钥序列在不到100万字节内就发生了完全的重复,如果是部分重复,则可能在不到10万字节内就能发生重复,因此,推荐在使用RC4算法时,必须对加密密钥进行测试,判断其是否为弱密钥。

​  Maven

<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.9</version>
</dependency>
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>

  工具类实现

  RC4Util提供了针对文本内容、字节数组内容的加解密实现,RC4Util工具类可以直接复制使用,代码如下:

package com.arhorchin.securitit.enordecryption.rc4;

import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;

/**
 * @author Securitit.
 * @note RC4加密算法实现.
 */
public class RC4Util {
    
    

    /**
     * logger.
     */
    private static Logger logger = Logger.getLogger(RC4Util.class);

    /**
     * UTF-8字符集.
     */
    public final static String CHARSET_UTF8 = "UTF-8";

    /**
     * 对文本内容进行加密.
     * @param plainText 待加密明文内容.
     * @param rc4Key RC4密钥.
     * @return 加密的密文.
     */
    public static String encodeText(String plainText, String rc4Key) throws Exception {
    
    
        byte[] plainBytes = null;
        byte[] cipherBytes = null;

        try {
    
    
            plainBytes = plainText.getBytes(CHARSET_UTF8);
            cipherBytes = rc4EnOrDecode(plainBytes, rc4Key);
            return Base64.encodeBase64String(cipherBytes);
        } catch (Exception ex) {
    
    
            logger.error("RC4Util.encodeText.", ex);
            return "";
        }
    }

    /**
     * 对文本密文进行解密.
     * @param cipherText 待解密密文.
     * @param rc4Key RC4密钥.
     * @return 解密的明文.
     */
    public static String decodeText(String cipherText, String rc4Key) throws Exception {
    
    
        byte[] cipherBytes = null;
        byte[] plainBytes = null;

        try {
    
    
            cipherBytes = Base64.decodeBase64(cipherText);
            plainBytes = rc4EnOrDecode(cipherBytes, rc4Key);
            return new String(plainBytes, CHARSET_UTF8);
        } catch (Exception ex) {
    
    
            logger.error("DESUtil.decodeText.", ex);
            return "";
        }
    }

    /**
     * 对字节数组内容进行加密.
     * @param plainText 待加密明文内容.
     * @param rc4Key RC4密钥.
     * @return 加密的密文.
     */
    public static byte[] encodeBytes(byte[] plainBytes, String rc4Key) throws Exception {
    
    
        byte[] cipherBytes = null;

        try {
    
    
            cipherBytes = rc4EnOrDecode(plainBytes, rc4Key);
            return cipherBytes;
        } catch (Exception ex) {
    
    
            logger.error("DESUtil.encodeBytes.", ex);
            return new byte[0];
        }
    }

    /**
     * 对字节数组密文进行解密.
     * @param cipherText 待解密密文.
     * @param rc4Key RC4密钥.
     * @return 解密的明文.
     */
    public static byte[] decodeBytes(byte[] cipherBytes, String rc4Key) throws Exception {
    
    
        byte[] plainBytes = null;

        try {
    
    
            plainBytes = rc4EnOrDecode(cipherBytes, rc4Key);
            return plainBytes;
        } catch (Exception ex) {
    
    
            logger.error("DESUtil.decodeBytes.", ex);
            return new byte[0];
        }
    }

    /**
     * 初始化RC4密钥.
     * @param rc4Key RC4密钥.
     * @return 初始化后的密钥.
     * @throws 可能的异常.
     */
    private static byte[] rc4InitKey(String rc4Key) throws Exception {
    
    
        byte[] keyBytes = null;
        byte[] keyState = null;
        int indexFirst = 0;
        int indexSecond = 0;
        // 变量初始化.
        keyBytes = rc4Key.getBytes(CHARSET_UTF8);
        keyState = new byte[256];
        for (int i = 0; i < 256; i++) {
    
    
            keyState[i] = (byte) i;
        }
        // 进行初始化.
        if (keyBytes == null || keyBytes.length == 0) {
    
    
            return null;
        }
        for (int i = 0; i < 256; i++) {
    
    
            indexSecond = ((keyBytes[indexFirst] & 0xff) + (keyState[i] & 0xff) + indexSecond) & 0xff;
            byte tmp = keyState[i];
            keyState[i] = keyState[indexSecond];
            keyState[indexSecond] = tmp;
            indexFirst = (indexFirst + 1) % keyBytes.length;
        }
        return keyState;
    }

    /**
     * RC4算法进行加解密.
     * @param bytes 待处理内容.
     * @param rc4Key RC4密钥.
     * @return 处理后结果内容.
     * @throws 可能的异常.
     */
    public static byte[] rc4EnOrDecode(byte[] bytes, String rc4Key) throws Exception {
    
    
        int x = 0;
        int y = 0;
        byte key[] = rc4InitKey(rc4Key);
        int xorIndex;
        byte[] result = new byte[bytes.length];
        // 数据加密.
        for (int i = 0; i < bytes.length; i++) {
    
    
            x = (x + 1) & 0xff;
            y = ((key[x] & 0xff) + y) & 0xff;
            byte tmp = key[x];
            key[x] = key[y];
            key[y] = tmp;
            xorIndex = ((key[x] & 0xff) + (key[y] & 0xff)) & 0xff;
            result[i] = (byte) (bytes[i] ^ key[xorIndex]);
        }
        return result;
    }

}

  工具类测试

  在Maven依赖引入正确的情况下,复制上面的代码到项目中,修改package,可以直接使用,下面我们对工具类进行简单测试。测试类代码如下:

package com.arhorchin.securitit.enordecryption.rc4;

import java.util.Arrays;

/**
 * @author Securitit.
 * @note RC4Util测试类.
 */
public class RC4UtilTester {
    
    

    public static void main(String[] args) throws Exception {
    
    
        String rc4Key = "1234567887654321";
        String plainText = "This is 一段明文内容!";
        String cipherText = null;

        // 文本加解密测试.
        System.out.println("----------------------- 文本加解密测试 -------------------------");
        System.out.println("明文:" + plainText);
        cipherText = RC4Util.encodeText(plainText, rc4Key);
        System.out.println("密文:" + cipherText);
        plainText = RC4Util.decodeText(cipherText, rc4Key);
        System.out.println("解密明文:" + plainText);
        System.out.println();
        System.out.println("----------------------- 字节数组加解密测试 -------------------------");
        byte[] plainBytes = plainText.getBytes("UTF-8");
        byte[] cipherBytes = null;
        System.out.println("明文:" + Arrays.toString(plainBytes));
        cipherBytes = RC4Util.encodeBytes(plainBytes, rc4Key);
        System.out.println("密文:" + Arrays.toString(cipherBytes));
        plainBytes = RC4Util.decodeBytes(cipherBytes, rc4Key);
        System.out.println("解密明文:" + Arrays.toString(plainBytes));
        System.out.println();
    }
    
}

  控制台输出

  查看Console中的控制台内容,明文和解密后明文对比,可以确认RC4Util可以正常工作,控制台如下图:

----------------------- 文本加解密测试 -------------------------
明文:This is 一段明文内容!
密文:Soto24/zhWUvTbG/1nITEhyYyHSZu0qq4crcD5s=
解密明文:This is 一段明文内容!

----------------------- 字节数组加解密测试 -------------------------
明文:[84, 104, 105, 115, 32, 105, 115, 32, -28, -72, -128, -26, -82, -75, -26, -104, -114, -26, -106, -121, -27, -122, -123, -27, -82, -71, -17, -68, -127]
密文:[74, -117, 104, -37, -113, -13, -123, 101, 47, 77, -79, -65, -42, 114, 19, 18, 28, -104, -56, 116, -103, -69, 74, -86, -31, -54, -36, 15, -101]
解密明文:[84, 104, 105, 115, 32, 105, 115, 32, -28, -72, -128, -26, -82, -75, -26, -104, -114, -26, -106, -121, -27, -122, -123, -27, -82, -71, -17, -68, -127]

  总结

  RC4算法实现比较简单,均是按照算法实现。

  RC4算法在现如今的硬件和网络环境下已经显得很不安全,很有代表性的一个例子就是路由的密码保护策略,记不记得在几年前设置路由器的密码策略时,有一项可选的WEP,它就是IV和RC4的联合应用。有段时间,WIFI万能钥匙一类的应用层出不穷,正侧面体现了RC4在安全性方面的不足。现如今,甚至在一台普通的PC上,都可以在短时间内破解基于RC4的加密信息。RC4的应用正在逐渐减少,但存在即合理,在一些特定场景下,RC4还是存在它的用途。

​  若文中存在错误和不足,欢迎指正!

本博微信公众号“超哥说码”,欢迎大家订阅,公众号正在完善中,会及时将更优质的博文推送于您!
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/securitit/article/details/108208138