⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 securemesg.java

📁 用Java语言编写的数据传输小软件 基于P2P传输模式 可以多线程传送 类似于QQ 速度和QQ差不多
💻 JAVA
字号:
package util;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;

import rsa.RSACipher;
import des.DESCipher;

public class SecureMesg {
    private static int DEBUG = 1;

    public static void main(String[] a) throws Exception {
        SecureMesg secureMesg = new SecureMesg();
        secureMesg.initScr();
        if (a.length < 4) {
            System.out.println("Usage:");
            System.out.println("java cipher encrypt/decrypt keyFile"
                    + " msgFile cphFile");
            return;
        }
        String mode = a[0];
        String keyFile = a[1];
        String msgFile = a[2];
        String cphFile = a[3];
        try {
            if (mode.equalsIgnoreCase("encrypt")) {
                try {
                    secureMesg.encrypt(keyFile, msgFile, cphFile);
                } catch (FileNotFoundException e) {
                    System.out
                            .println("File not found, please check the existence of the key file and msg file you specified.\n "
                                    + e.getMessage());
                }
            } else if (mode.equalsIgnoreCase("decrypt")) {
                try {
                    secureMesg.decrypt(keyFile, msgFile, cphFile);
                } catch (FileNotFoundException e) {
                    System.out
                            .println("File not found, please check the existence of the key file and cph file you specified.\n"
                                    + e.getMessage());
                }
            } else {
                secureMesg.helpMesg();
            }
        } catch (IOException e) {
            System.out.println("I/O Exception: " + e.getMessage());
        }

    }

    /**
     * Initialize screen
     * 
     */
    public void initScr() {
        System.out
                .print("\n\t******************************************************************\n");
        System.out
                .print("\t|                                                                  |\n");
        System.out
                .print("\t|            Welcome to Security Cipher System !                   |\n");
        System.out
                .print("\t|                                                                  |\n");
        System.out
                .print("\t********************************************************************\n");
    }

    public void helpMesg() {
        System.out.println("Usage:");
        System.out.println("java cipher encrypt/decrypt keyFile"
                + " msgFile cphFile");

    }

    /**
     * Encrypt the msgFile to cphFile using key in keyFile
     * 
     * @param keyFile
     * @param msgFile
     * @param cphFile
     * @throws Exception
     * @throws Exception
     */
    public void encrypt(String keyFile, String msgFile, String cphFile)
            throws Exception {
        DESCipher desCipherTool = new DESCipher();
        FileOutputStream fos = new FileOutputStream(cphFile);

        byte[] theKey = this.readBytes(keyFile);
        byte[][] subKeys = desCipherTool.getSubkeys(theKey);
        byte[] theMsg = this.readBytes(msgFile);
        this.printBytes(theKey, "Key block");

        if (DEBUG == 0) {
            this.printBytes(theKey, "Key block");
            this.printBytes(theMsg, "Msg block");
        }
        // put the cipher Key at the beginning of the ciphered file
        RSACipher rsaCipherTool = new RSACipher(512);
        BigInteger cipherKey;
        BigInteger keyInt = new BigInteger(theKey);
        cipherKey = rsaCipherTool.RSAEncrypt(keyInt);
        // first write the cipher key's length, then cipher key, then ciphered
        // text
        fos.write(cipherKey.toByteArray().length);
        fos.write(cipherKey.toByteArray());
        if (DEBUG == 0) {
            System.out.println("cipherKey.toByteArray().length:"
                    + cipherKey.toByteArray().length);
            this.printBytes(cipherKey.toByteArray(), "cipherKey");
        }

        // Split the text to 64bit blocks
        byte[][] plainText = splitPlainText(theMsg);
        if (DEBUG == 0) {
            for (int t = 0; t < plainText.length; t++) {
                this.printBytes(plainText[t], "plainText[" + t + "]");
            }
        }

        byte[][] cipherText = new byte[plainText.length][];
        for (int i = 0; i < plainText.length; i++) {
            cipherText[i] = desCipherTool.cipher(plainText[i], subKeys,
                    "encrypt");
            fos.write(cipherText[i]);
            if (DEBUG == 0) {
                this.printBytes(plainText[i], "plainText[" + i + "]");
                this.printBytes(cipherText[i], "cipherText[" + i + "]");
            }
        }

        fos.close();

        System.out.println("Encrypt Complete!");
        System.out
                .println("Please see " + cphFile + " for the encrypted file.");
    }

    /**
     * Decrypt cphFile to msgFile using key in keyFile
     * 
     * @param keyFile
     * @param msgFile
     * @param cphFile
     * @throws Exception
     */
    public void decrypt(String keyFile, String msgFile, String cphFile)
            throws Exception {
        DESCipher desCipherTool = new DESCipher();
        RSACipher rsaCipherTool = new RSACipher(1024);

        FileInputStream fis = new FileInputStream(cphFile);
        int numOfBytes = fis.available();
        int lenOfChKey = fis.read();
        byte[] keybuffer = new byte[lenOfChKey];
        fis.read(keybuffer);

        if (DEBUG == 0) {
            this.printBytes(keybuffer, "keybuffer");
        }

        // descrypt the key using RSA
        BigInteger keyInt = new BigInteger(keybuffer);
        byte[] theKey = rsaCipherTool.RSADecrypt(keyInt).toByteArray();

        if (DEBUG == 0) {
            this.printBytes(theKey, "Decrypted Key Block");
        }

        byte[][] subKeys = desCipherTool.getSubkeys(theKey);

        FileOutputStream fos = new FileOutputStream(msgFile);

        numOfBytes = numOfBytes - 1 - lenOfChKey;
        byte[] buffer = new byte[8];
        byte[] bufferout = new byte[8];
        int len = numOfBytes / 8;
        for (int i = 0; i < len; i++) {
            fis.read(buffer);
            bufferout = desCipherTool.cipher(buffer, subKeys, "decrypt");

            if (DEBUG == 0) {
                this.printBytes(bufferout, "bufferout");
            }

            fos.write(bufferout);
        }
        fis.close();
        fos.close();

        this.printBytes(theKey, "Key block");

        System.out.println("Decrypt Complete!");
        System.out
                .println("Please see " + msgFile + " for the decrypted file.");

    }

    /**
     * Split plain text to an array of 8-byte(64 bits) array
     * 
     * @param theMsg
     * @return an array of 8-byte(64 bits) array
     */
    public byte[][] splitPlainText(byte[] theMsg) {
        int blockNum = theMsg.length / 8;
        byte[] tmpMsg = (byte[]) theMsg.clone();
        theMsg = new byte[tmpMsg.length + 1];
        for (int t = 0; t < tmpMsg.length; t++) {
            theMsg[t] = tmpMsg[t];
        }
        if ((blockNum * 8) < theMsg.length) {
            // Could not be divided exactly by 64 bits,
            // add a byte indicating the last byte's number of bit
            blockNum = blockNum + 1;
            theMsg[tmpMsg.length] = (byte) (tmpMsg.length % 8);
        } else {
            // Can be divided exactly by 64 bits
            theMsg[tmpMsg.length] = (byte) 0;
        }
        byte[][] plainText = new byte[blockNum][];
        int i;
        for (i = 0; i < (blockNum - 1); i++) {
            plainText[i] = new byte[8];
            for (int j = 0; j < 8; j++) {
                plainText[i][j] = theMsg[i * 8 + j];
            }
        }
        if (theMsg[tmpMsg.length] > 0) {
            int j;
            for (j = 0; j < tmpMsg.length % 8; j++) {
                plainText[i] = new byte[8];
                plainText[i][j] = theMsg[i * 8 + j];
            }
            while (j < 8) {
                plainText[i][j] = (byte) 0;
                j++;
            }
        } else {
            for (int j = 0; j < 8; j++) {
                plainText[i][j] = theMsg[i * 8 + j];
            }
        }
        return plainText;
    }

    /**
     * Function: Print the bits in byte array
     * 
     * @param data
     * @param name
     */
    public void printBytes(byte[] data, String name) {
        System.out.println("");
        System.out.println(name + ":");
        for (int i = 0; i < data.length; i++) {
            System.out.print(byteToBits(data[i]) + " ");
        }
        System.out.println();
    }

    /**
     * Function: Turn byte to bits
     * 
     * @param b
     * @return
     */
    private String byteToBits(byte b) {
        StringBuffer buf = new StringBuffer();
        for (int i = 0; i < 8; i++)
            buf.append((int) (b >> (8 - (i + 1)) & 0x0001));
        return buf.toString();
    }

    /**
     * Function: Read bytes from a file and get a byte[]
     * 
     * @param in
     * @return
     * @throws Exception
     */
    public byte[] readBytes(String in) throws Exception {
        FileInputStream fis = new FileInputStream(in);
        int numOfBytes = fis.available();
        byte[] buffer = new byte[numOfBytes];
        fis.read(buffer);
        fis.close();
        return buffer;
    }

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -