Java implementation of XOR algorithm encryption and decryption

Link to this article: https://blog.csdn.net/xietansheng/article/details/88420949

1. xor encryption principle

If an integer a and any integer b are exclusive or twice, the result is the integer a itself, that is: a == a ^ b ^ b.

Here a is the original data to be encrypted, and b is the key. A ^ b is the encryption process, and the result of exclusive or is the encrypted ciphertext; a ^ b and key b exclusive or are the decryption process, and the result is the original data a itself.

a = Original data
b = secret key

// One XOR, encrypted to ciphertext
c = a ^ b

// Second exclusive or, decrypt to get the original data (d == a)
d = c ^ b

XOR encryption if the original and ciphertext are known at the same time, the secret key can be calculated by comparing the original and the password. Therefore, XOR encryption has low security and is generally only used for simple encryption.

2. XOR encryption code instance

2.1 XOR encryption tool class encapsulation: XORUtils

XORUtils.java full source code:

package com.xiets.xor;

import java.io.BufferedOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * XOR algorithm encryption / decryption tool
 *
 * @author xietansheng
 */
public class XORUtils {

    /**
     * XOR algorithm encryption / decryption
     *
     * @param data Data (ciphertext / clear text)
     * @param key secret key
     * @return Return decrypted / encrypted data
     */
    public static byte[] encrypt(byte[] data, byte[] key) {
        if (data == null || data.length == 0 || key == null || key.length == 0) {
            return data;
        }

        byte[] result = new byte[data.length];

        // Use key byte array to cycle encryption or decryption
        for (int i = 0; i < data.length; i++) {
            // Data is XOR with key, and then XOR with low 8 bits of cyclic variable (increasing complexity)
            result[i] = (byte) (data[i] ^ key[i % key.length] ^ (i & 0xFF));
        }

        return result;
    }

    /**
     * Encrypt / decrypt file XOR algorithm
     *
     * @param inFile Input file (ciphertext / clear text)
     * @param outFile Result output file
     * @param key secret key
     */
    public static void encryptFile(File inFile, File outFile, byte[] key) throws Exception {
        InputStream in = null;
        OutputStream out = null;

        try {
            // File input stream
            in = new FileInputStream(inFile);
            // The result output stream, exclusive or operation, byte is a read and write, where cache stream must be used,
            // Wait until the cache reaches a certain number of bytes (10240 bytes) and then write to the disk (otherwise, write to the disk too many times and the speed will be very slow)
            out = new BufferedOutputStream(new FileOutputStream(outFile), 10240);

            int b = -1;
            long i = 0;

            // Read one byte of the file in each cycle, and use the key byte array to cycle encryption or decryption
            while ((b = in.read()) != -1) {
                // Data is XOR with key, and then XOR with low 8 bits of cyclic variable (increasing complexity)
                b = (b ^ key[(int) (i % key.length)] ^ (int) (i & 0xFF));
                // Write a byte after encryption / decryption
                out.write(b);
                // Loop variable increment
                i++;
            }
            out.flush();

        } finally {
            close(in);
            close(out);
        }
    }

    private static void close(Closeable c) {
        if (c != null) {
            try {
                c.close();
            } catch (IOException e) {
                // nothing
            }
        }
    }

}

XOR encryption and decryption use the same method. XORUtils class has two public static methods:

// Encrypt / decrypt byte array data
static byte[] encrypt(byte[] data, byte[] key)

// Encrypt / decrypt files
static void encryptFile(File inFile, File outFile, byte[] key)

2.2 use of xorutils tool class

package com.xiets.aes;

import com.xiets.xor.XORUtils;

import java.io.File;

/**
 * @author xietansheng
 */
public class Main {

    public static void main(String[] args) throws Exception {
        String content = "Hello world!";        // Original content
        String key = "123456";                  // Original password for XOR encryption / decryption

        // Encrypted data, return ciphertext
        byte[] cipherBytes = XORUtils.encrypt(content.getBytes(), key.getBytes());
        // Decrypt data, return clear text
        byte[] plainBytes = XORUtils.encrypt(cipherBytes, key.getBytes());
        // Output decrypted plaintext: "Hello world!"
        System.out.println(new String(plainBytes));

        /*
         * XOR Encryption / decryption of files
         */
        // Encrypt the file demo.java and output it to the file demo.jpg_cipher
        XORUtils.encryptFile(new File("demo.jpg"), new File("demo.jpg_cipher"), key.getBytes());
        // Decrypt and output the file demo.jpg \ cipher to the file demo.jpg \ plain
        XORUtils.encryptFile(new File("demo.jpg_cipher"), new File("demo.jpg_plain"), key.getBytes());

        // Comparing the original file demo.jpg with the decrypted file demo.jpg_plain, their MD5 will be exactly the same
    }

}

Tags: Java

Posted on Wed, 04 Dec 2019 03:36:41 -0500 by NathanS