異或加密工具

/**
 * 異或加密工具類
 * <p>
 * 位運(yùn)算可以實(shí)現(xiàn)很多高級(jí),高效的運(yùn)算。
 * 可用于 IM 二進(jìn)制數(shù)據(jù)包加密,第一能夠?qū)崿F(xiàn)加密,第二采用異或加密算法不會(huì)改變二進(jìn)制數(shù)據(jù)的長(zhǎng)度這對(duì)二進(jìn)制數(shù)據(jù)包封包起到不小的好處
 * 也可用于記事本等場(chǎng)景
 * <p>
 * 參考鏈接:http://www.cnblogs.com/whoislcj/p/5944917.html
 */
public final class XorUtil {

    private XorUtil() {
        throw new UnsupportedOperationException("cannot be instantiated");
    }

    /**
     * 固定 key 的方式加密
     * <p>
     * 這種方式加密解密 算法一樣
     * <p>
     * 加密:byte[] bytes = encryptAsFix("liyi".getBytes());
     * 解密:String str = new String(encryptAsFix(bytes));
     *
     * @param bytes 待加密數(shù)據(jù)
     * @return 加密后的數(shù)據(jù)
     */
    public static byte[] encryptAsFix(byte[] bytes) {
        if (bytes == null) {
            return null;
        }
        int len = bytes.length;
        int key = 0x12;
        for (int i = 0; i < len; i++) {
            bytes[i] ^= key;
        }
        return bytes;
    }


    /**
     * 非固定 key 的方式加密
     *
     * @param bytes 待加密數(shù)據(jù)
     * @return 加密后的數(shù)據(jù)
     */
    public static byte[] encrypt(byte[] bytes) {
        if (bytes == null) {
            return null;
        }
        int len = bytes.length;
        int key = 0x12;
        for (int i = 0; i < len; i++) {
            bytes[i] = (byte) (bytes[i] ^ key);
            key = bytes[i];
        }
        return bytes;
    }

    /**
     * 解密
     *
     * @param bytes 待解密數(shù)據(jù)
     * @return 解密后的數(shù)據(jù)
     */
    public byte[] decrypt(byte[] bytes) {
        if (bytes == null) {
            return null;
        }
        int len = bytes.length;
        int key = 0x12;
        for (int i = len - 1; i > 0; i--) {
            bytes[i] = (byte) (bytes[i] ^ bytes[i - 1]);
        }
        bytes[0] = (byte) (bytes[0] ^ key);
        return bytes;
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容