[DES detailed explanation] (2) Processing strings (unlimited bits)

[DES Detailed Explanation] (1) Processing input block (64 bits)

Detailed code

//DES.java
public class DES {
    
    
    public static String encryption(String input, String secret_key) {
    
    
        StringBuffer res_cipher = new StringBuffer();
        
        //1、将输入和密钥(String)转换成二进制(String)
        input = Operation.strToBinStr(input);
        secret_key = Operation.strToBinStr(secret_key);
        
        //2、填充二进制输入
        input = Operation.pad(input);
        
        //3、分block(64 bits)加密二进制输入
        int pad_len = Operation.pad_len;
        for (int epoch = 0; epoch < input.length(); epoch += 64) {
    
    
            Operation op = new Operation();
            Unit unit = new Unit(secret_key, op);
            unit.encryption(input.substring(epoch, epoch + 64));
            res_cipher.append(unit.cipher_text);
        }
        
        //4、输出格式:填充位数#密文
        String cipher = pad_len + "#" + res_cipher;
        
        Operation.writeToFile(cipher, false);
        return cipher;
    }

    public static String decryption(String input, String secret_key) {
    
    
        StringBuffer res_plain = new StringBuffer();
        
        //1、将“密文”(String)转换成二进制(String)
        secret_key = Operation.strToBinStr(secret_key);
        
        //2、“密文” = 填充位数 + 密文
        String[] strings = input.split("#");
        int pad_len = Integer.parseInt(strings[0]);
        input = strings[1];
        
        //3、分block(64 bits)解密密文
        for (int epoch = 0; epoch < input.length(); epoch += 64) {
    
    
            Operation op = new Operation();
            Unit unit = new Unit(secret_key, op);
            unit.decryption(input.substring(epoch, epoch + 64));
            res_plain.append(unit.plain_text);
        }
        
        //4、去除填充位,输出明文
        return Operation.binStrToStr(res_plain.substring(pad_len));
    }
}
//Operation.java
public static String strToBinStr(String str) {
    
    
    byte[] bytes = str.getBytes(Charset.forName("UTF-8")); // 将字符串转换为UTF-8编码的字节数组
    StringBuilder binary = new StringBuilder();
    for (byte b : bytes) {
    
    
        int val = b;
        for (int i = 0; i < 8; i++) {
    
    
            binary.append((val & 128) == 0 ? 0 : 1);
            val <<= 1;
        }
    }
    return binary.toString(); // 将字节数组转换为二进制字符串
}

public static String binStrToStr(String binaryString) {
    
    
    int byteLen = binaryString.length() / 8;
    byte[] bytes = new byte[byteLen];
    for (int i = 0; i < byteLen; i++) {
    
    
        bytes[i] = (byte) Integer.parseInt(binaryString.substring(i * 8, (i + 1) * 8), 2); // 将二进制字符串转换为字节数组
    }
    return new String(bytes, Charset.forName("UTF-8")); // 将字节数组转换为字符串,使用UTF-8字符编码方式
}

Guess you like

Origin blog.csdn.net/m0_60641871/article/details/130148287