Java开发实例大全提高篇——Java安全

2024-09-08 00:32

本文主要是介绍Java开发实例大全提高篇——Java安全,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

开发十年,就只剩下这套架构体系了! >>>   hot3.png

第6篇  Java安全与Applet应用篇
第20章  Java安全
20.1  Java对称加密
实例531  使用BASE64加密
    public static String encryptBASE64(byte[] data) {
        //加密数据
        return (new BASE64Encoder()).encodeBuffer(data);
    }

    /**
     * 解密
     *
     * @param data
     * @return
     * @throws IOException
     */
    public static byte[] decryptBASE64(String data) throws IOException {
        //解密数据
        return (new BASE64Decoder()).decodeBuffer(data);
    }

    public static void main(String[] avg) throws IOException {
        String data = "明日科技";
        System.out.println("加密前:" + data);
        String data1 = BothBase64.encryptBASE64(data.getBytes());
        System.out.println("加密后:" + data1);
        byte[] data2 = BothBase64.decryptBASE64(data1);
        System.out.println("解密后:" + new String(data2));
    }

实例532  使用BASE64解密
    public static String encryptBASE64(byte[] data) {
        //加密数据
        return (new BASE64Encoder()).encodeBuffer(data);
    }

    /**
     * 解密
     *
     * @param data
     * @return
     * @throws IOException
     */
    public static byte[] decryptBASE64(String data) throws IOException {
        //解密数据
        return (new BASE64Decoder()).decodeBuffer(data);
    }

    public static void main(String[] avg) throws IOException {
        String data = "明日科技";
        System.out.println("加密前:" + data);
        String data1 = BothBase64.encryptBASE64(data.getBytes());
        System.out.println("加密后:" + data1);
        byte[] data2 = BothBase64.decryptBASE64(data1);
        System.out.println("解密后:" + new String(data2));
    }

实例533  生成DES的密钥
    String algorithm = "DES";
    // key保存的文件名称
    String keyFile = "keyData.dat";
    // 数据保存的文件名称
    String dataFile = "fileData.dat";

    public BothDESFile() {
        try {
            initKey();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 生成密钥数据,保存到文件中
     *
     * @throws NoSuchAlgorithmException
     */
    private void initKey() throws NoSuchAlgorithmException {
        // 产生一个随机数源
        SecureRandom secureRandom = new SecureRandom();
        // 为DES算法生成一个KeyGenerator
        KeyGenerator generator = KeyGenerator.getInstance(algorithm);
        generator.init(secureRandom);
        SecretKey key = generator.generateKey();
        //生成密钥数据,保存到文件中
        writeFile(key.getEncoded(), keyFile);

    }

    /**
     * 转化密钥成Key进行加密解密
     *
     * @return
     * @throws InvalidKeyException
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeySpecException
     */
    private Key toKey() throws InvalidKeyException, NoSuchAlgorithmException,
            InvalidKeySpecException {
        byte[] key = readFile(keyFile);
        DESKeySpec keySpec = new DESKeySpec(key);
        SecretKeyFactory factory = SecretKeyFactory.getInstance(algorithm);
        SecretKey secretKey = factory.generateSecret(keySpec);
        return secretKey;
    }

    /**
     * 加密,把加密数据保存在文件中
     *
     * @param data
     * @param key
     * @throws InvalidKeyException
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeySpecException
     * @throws NoSuchPaddingException
     * @throws IllegalBlockSizeException
     * @throws BadPaddingException
     */
    public void encrypt(byte[] data) throws InvalidKeyException,
            NoSuchAlgorithmException, InvalidKeySpecException,
            NoSuchPaddingException, IllegalBlockSizeException,
            BadPaddingException {
        Key key = toKey();
        // 使用Cipher实际完成加密操作
        Cipher cipher = Cipher.getInstance(algorithm);
        // 使用密钥初始化Cipher
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] f = cipher.doFinal(data);
        writeFile(f, dataFile);
    }

    /**
     * 解密把数据从文件中取出来在解密
     *
     * @param data
     * @param key
     * @return
     * @throws InvalidKeyException
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeySpecException
     * @throws NoSuchPaddingException
     * @throws IllegalBlockSizeException
     * @throws BadPaddingException
     */
    public String decrypt() throws InvalidKeyException,
            NoSuchAlgorithmException, InvalidKeySpecException,
            NoSuchPaddingException, IllegalBlockSizeException,
            BadPaddingException {
        Key key = toKey();
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] f = readFile(dataFile);
        return new String(cipher.doFinal(f));
    }

    /**
     * 把数据写到指定的文件上
     *
     * @param data
     *            数据
     * @param fileName
     *            文件名称
     */
    public void writeFile(byte[] data, String fileName) {
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(fileName);
            fileOutputStream.write(data);
            fileOutputStream.close();

        } catch (FileNotFoundException e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 根据fileName读取数据文件
     *
     * @param fileName
     * @return
     */
    public byte[] readFile(String fileName) {

        // 读取
        try {
            File file = new File(fileName);
            FileInputStream fileInputStream = new FileInputStream(file);
            byte[] data = new byte[(int) file.length()];
            fileInputStream.read(data);
            fileInputStream.close();
            return data;
        } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;

    }

    public static void main(String[] avg) throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
        BothDESFile bothDESFile = new BothDESFile();
        String data = "明日科技";

        // 数据加密
        System.out.println("加密前:" + data);
        bothDESFile.encrypt(data.getBytes());

        // 数据解密
        String b = bothDESFile.decrypt();
        System.out.println("解密后:" + b);

    }

实例534  使用DES加密
    String algorithm = "DES";
    // key保存的文件名称
    String keyFile = "keyData.dat";
    // 数据保存的文件名称
    String dataFile = "fileData.dat";

    public BothDESFile() {
        try {
            initKey();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 生成密钥数据,保存到文件中
     *
     * @throws NoSuchAlgorithmException
     */
    private void initKey() throws NoSuchAlgorithmException {
        // 产生一个随机数源
        SecureRandom secureRandom = new SecureRandom();
        // 为DES算法生成一个KeyGenerator
        KeyGenerator generator = KeyGenerator.getInstance(algorithm);
        generator.init(secureRandom);
        SecretKey key = generator.generateKey();
        //生成密钥数据,保存到文件中
        writeFile(key.getEncoded(), keyFile);

    }

    /**
     * 转化密钥成Key进行加密解密
     *
     * @return
     * @throws InvalidKeyException
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeySpecException
     */
    private Key toKey() throws InvalidKeyException, NoSuchAlgorithmException,
            InvalidKeySpecException {
        byte[] key = readFile(keyFile);
        DESKeySpec keySpec = new DESKeySpec(key);
        SecretKeyFactory factory = SecretKeyFactory.getInstance(algorithm);
        SecretKey secretKey = factory.generateSecret(keySpec);
        return secretKey;
    }

    /**
     * 加密,把加密数据保存在文件中
     *
     * @param data
     * @param key
     * @throws InvalidKeyException
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeySpecException
     * @throws NoSuchPaddingException
     * @throws IllegalBlockSizeException
     * @throws BadPaddingException
     */
    public void encrypt(byte[] data) throws InvalidKeyException,
            NoSuchAlgorithmException, InvalidKeySpecException,
            NoSuchPaddingException, IllegalBlockSizeException,
            BadPaddingException {
        Key key = toKey();
        // 使用Cipher实际完成加密操作
        Cipher cipher = Cipher.getInstance(algorithm);
        // 使用密钥初始化Cipher
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] f = cipher.doFinal(data);
        writeFile(f, dataFile);
    }

    /**
     * 解密把数据从文件中取出来在解密
     *
     * @param data
     * @param key
     * @return
     * @throws InvalidKeyException
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeySpecException
     * @throws NoSuchPaddingException
     * @throws IllegalBlockSizeException
     * @throws BadPaddingException
     */
    public String decrypt() throws InvalidKeyException,
            NoSuchAlgorithmException, InvalidKeySpecException,
            NoSuchPaddingException, IllegalBlockSizeException,
            BadPaddingException {
        Key key = toKey();
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] f = readFile(dataFile);
        return new String(cipher.doFinal(f));
    }

    /**
     * 把数据写到指定的文件上
     *
     * @param data
     *            数据
     * @param fileName
     *            文件名称
     */
    public void writeFile(byte[] data, String fileName) {
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(fileName);
            fileOutputStream.write(data);
            fileOutputStream.close();

        } catch (FileNotFoundException e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 根据fileName读取数据文件
     *
     * @param fileName
     * @return
     */
    public byte[] readFile(String fileName) {

        // 读取
        try {
            File file = new File(fileName);
            FileInputStream fileInputStream = new FileInputStream(file);
            byte[] data = new byte[(int) file.length()];
            fileInputStream.read(data);
            fileInputStream.close();
            return data;
        } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;

    }

    public static void main(String[] avg) throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
        BothDESFile bothDESFile = new BothDESFile();
        String data = "明日科技";

        // 数据加密
        System.out.println("加密前:" + data);
        bothDESFile.encrypt(data.getBytes());

        // 数据解密
        String b = bothDESFile.decrypt();
        System.out.println("解密后:" + b);

    }

实例535  使用DES解密
    String algorithm = "DES";
    // key保存的文件名称
    String keyFile = "keyData.dat";
    // 数据保存的文件名称
    String dataFile = "fileData.dat";

    public BothDESFile() {
        try {
            initKey();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 生成密钥数据,保存到文件中
     *
     * @throws NoSuchAlgorithmException
     */
    private void initKey() throws NoSuchAlgorithmException {
        // 产生一个随机数源
        SecureRandom secureRandom = new SecureRandom();
        // 为DES算法生成一个KeyGenerator
        KeyGenerator generator = KeyGenerator.getInstance(algorithm);
        generator.init(secureRandom);
        SecretKey key = generator.generateKey();
        //生成密钥数据,保存到文件中
        writeFile(key.getEncoded(), keyFile);

    }

    /**
     * 转化密钥成Key进行加密解密
     *
     * @return
     * @throws InvalidKeyException
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeySpecException
     */
    private Key toKey() throws InvalidKeyException, NoSuchAlgorithmException,
            InvalidKeySpecException {
        byte[] key = readFile(keyFile);
        DESKeySpec keySpec = new DESKeySpec(key);
        SecretKeyFactory factory = SecretKeyFactory.getInstance(algorithm);
        SecretKey secretKey = factory.generateSecret(keySpec);
        return secretKey;
    }

    /**
     * 加密,把加密数据保存在文件中
     *
     * @param data
     * @param key
     * @throws InvalidKeyException
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeySpecException
     * @throws NoSuchPaddingException
     * @throws IllegalBlockSizeException
     * @throws BadPaddingException
     */
    public void encrypt(byte[] data) throws InvalidKeyException,
            NoSuchAlgorithmException, InvalidKeySpecException,
            NoSuchPaddingException, IllegalBlockSizeException,
            BadPaddingException {
        Key key = toKey();
        // 使用Cipher实际完成加密操作
        Cipher cipher = Cipher.getInstance(algorithm);
        // 使用密钥初始化Cipher
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] f = cipher.doFinal(data);
        writeFile(f, dataFile);
    }

    /**
     * 解密把数据从文件中取出来在解密
     *
     * @param data
     * @param key
     * @return
     * @throws InvalidKeyException
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeySpecException
     * @throws NoSuchPaddingException
     * @throws IllegalBlockSizeException
     * @throws BadPaddingException
     */
    public String decrypt() throws InvalidKeyException,
            NoSuchAlgorithmException, InvalidKeySpecException,
            NoSuchPaddingException, IllegalBlockSizeException,
            BadPaddingException {
        Key key = toKey();
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] f = readFile(dataFile);
        return new String(cipher.doFinal(f));
    }

    /**
     * 把数据写到指定的文件上
     *
     * @param data
     *            数据
     * @param fileName
     *            文件名称
     */
    public void writeFile(byte[] data, String fileName) {
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(fileName);
            fileOutputStream.write(data);
            fileOutputStream.close();

        } catch (FileNotFoundException e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 根据fileName读取数据文件
     *
     * @param fileName
     * @return
     */
    public byte[] readFile(String fileName) {

        // 读取
        try {
            File file = new File(fileName);
            FileInputStream fileInputStream = new FileInputStream(file);
            byte[] data = new byte[(int) file.length()];
            fileInputStream.read(data);
            fileInputStream.close();
            return data;
        } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;

    }

    public static void main(String[] avg) throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
        BothDESFile bothDESFile = new BothDESFile();
        String data = "明日科技";

        // 数据加密
        System.out.println("加密前:" + data);
        bothDESFile.encrypt(data.getBytes());

        // 数据解密
        String b = bothDESFile.decrypt();
        System.out.println("解密后:" + b);

    }

实例536  PBE的盐值
    String algorithm = "PBEWithMD5AndDES";

    String saltFile = "saltData.dat";
    String dataFile = "fileData.dat";

    /**
     * 获取盐值
     *
     * @return
     * @throws Exception
     */
    public void initSalt() {
        byte[] salt = new byte[8];
        Random random = new Random();
        //生成随机数
        random.nextBytes(salt);
        //保存盐值
        writeFile(salt, saltFile);
    }

    /**
     * 获取钥匙
     *
     * @param password
     * @return
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeySpecException
     */
    private Key toKey(String password) throws NoSuchAlgorithmException,
            InvalidKeySpecException {
        PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algorithm);
        SecretKey secretKey = keyFactory.generateSecret(keySpec);
        return secretKey;
    }

    /**
     * 加密
     *
     * @param data
     * @param password
     * @throws InvalidKeySpecException
     * @throws NoSuchAlgorithmException
     * @throws NoSuchPaddingException
     * @throws InvalidAlgorithmParameterException
     * @throws InvalidKeyException
     * @throws BadPaddingException
     * @throws IllegalBlockSizeException
     */
    public void encrypt(byte[] data, String password)
            throws NoSuchAlgorithmException, InvalidKeySpecException,
            NoSuchPaddingException, InvalidKeyException,
            InvalidAlgorithmParameterException, IllegalBlockSizeException,
            BadPaddingException {
        Key key = toKey(password);
        byte[] salt = readFile(saltFile);
        PBEParameterSpec paramSpec = new PBEParameterSpec(salt, 100);
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
        writeFile(cipher.doFinal(data), dataFile);

    }

    /**
     * 解密
     *
     * @param data
     * @param password
     * @return
     * @throws InvalidKeySpecException
     * @throws NoSuchAlgorithmException
     * @throws NoSuchPaddingException
     * @throws InvalidAlgorithmParameterException
     * @throws InvalidKeyException
     * @throws BadPaddingException
     * @throws IllegalBlockSizeException
     */
    public String decrypt(String password) throws NoSuchAlgorithmException,
            InvalidKeySpecException, NoSuchPaddingException,
            InvalidKeyException, InvalidAlgorithmParameterException,
            IllegalBlockSizeException, BadPaddingException {
        Key key = toKey(password);
        byte[] salt = readFile(saltFile);
        byte[] data = readFile(dataFile);
        PBEParameterSpec paramSpec = new PBEParameterSpec(salt, 100);
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
        return new String(cipher.doFinal(data));
    }

    /**
     * 把数据写到指定的文件上
     *
     * @param data
     *            数据
     * @param fileName
     *            文件名称
     */
    public void writeFile(byte[] data, String fileName) {
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(fileName);
            fileOutputStream.write(data);
            fileOutputStream.close();
        } catch (FileNotFoundException e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 根据fileName读取数据文件
     *
     * @param fileName
     * @return
     */
    public byte[] readFile(String fileName) {

        // 读取
        try {
            File file = new File(fileName);
            FileInputStream fileInputStream = new FileInputStream(file);
            byte[] data = new byte[(int) file.length()];
            fileInputStream.read(data);
            fileInputStream.close();
            return data;
        } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;

    }

    public static void main(String[] avg) {
        BothPBEFile bothPBEFile = new BothPBEFile();
        String data = "明日科技";
        String password = "123456";
        System.out.println("加密前:" + data);
        try {
            bothPBEFile.initSalt();
            bothPBEFile.encrypt(data.getBytes(), password);
            String tdata = bothPBEFile.decrypt(password);
            System.out.println("解密后:" + tdata);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

实例537  生成PBE的密钥
    String algorithm = "PBEWithMD5AndDES";

    String saltFile = "saltData.dat";
    String dataFile = "fileData.dat";

    /**
     * 获取盐值
     *
     * @return
     * @throws Exception
     */
    public void initSalt() {
        byte[] salt = new byte[8];
        Random random = new Random();
        //生成随机数
        random.nextBytes(salt);
        //保存盐值
        writeFile(salt, saltFile);
    }

    /**
     * 获取钥匙
     *
     * @param password
     * @return
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeySpecException
     */
    private Key toKey(String password) throws NoSuchAlgorithmException,
            InvalidKeySpecException {
        PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algorithm);
        SecretKey secretKey = keyFactory.generateSecret(keySpec);
        return secretKey;
    }

    /**
     * 加密
     *
     * @param data
     * @param password
     * @throws InvalidKeySpecException
     * @throws NoSuchAlgorithmException
     * @throws NoSuchPaddingException
     * @throws InvalidAlgorithmParameterException
     * @throws InvalidKeyException
     * @throws BadPaddingException
     * @throws IllegalBlockSizeException
     */
    public void encrypt(byte[] data, String password)
            throws NoSuchAlgorithmException, InvalidKeySpecException,
            NoSuchPaddingException, InvalidKeyException,
            InvalidAlgorithmParameterException, IllegalBlockSizeException,
            BadPaddingException {
        Key key = toKey(password);
        byte[] salt = readFile(saltFile);
        PBEParameterSpec paramSpec = new PBEParameterSpec(salt, 100);
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
        writeFile(cipher.doFinal(data), dataFile);

    }

    /**
     * 解密
     *
     * @param data
     * @param password
     * @return
     * @throws InvalidKeySpecException
     * @throws NoSuchAlgorithmException
     * @throws NoSuchPaddingException
     * @throws InvalidAlgorithmParameterException
     * @throws InvalidKeyException
     * @throws BadPaddingException
     * @throws IllegalBlockSizeException
     */
    public String decrypt(String password) throws NoSuchAlgorithmException,
            InvalidKeySpecException, NoSuchPaddingException,
            InvalidKeyException, InvalidAlgorithmParameterException,
            IllegalBlockSizeException, BadPaddingException {
        Key key = toKey(password);
        byte[] salt = readFile(saltFile);
        byte[] data = readFile(dataFile);
        PBEParameterSpec paramSpec = new PBEParameterSpec(salt, 100);
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
        return new String(cipher.doFinal(data));
    }

    /**
     * 把数据写到指定的文件上
     *
     * @param data
     *            数据
     * @param fileName
     *            文件名称
     */
    public void writeFile(byte[] data, String fileName) {
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(fileName);
            fileOutputStream.write(data);
            fileOutputStream.close();
        } catch (FileNotFoundException e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 根据fileName读取数据文件
     *
     * @param fileName
     * @return
     */
    public byte[] readFile(String fileName) {

        // 读取
        try {
            File file = new File(fileName);
            FileInputStream fileInputStream = new FileInputStream(file);
            byte[] data = new byte[(int) file.length()];
            fileInputStream.read(data);
            fileInputStream.close();
            return data;
        } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;

    }

    public static void main(String[] avg) {
        BothPBEFile bothPBEFile = new BothPBEFile();
        String data = "明日科技";
        String password = "123456";
        System.out.println("加密前:" + data);
        try {
            bothPBEFile.initSalt();
            bothPBEFile.encrypt(data.getBytes(), password);
            String tdata = bothPBEFile.decrypt(password);
            System.out.println("解密后:" + tdata);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

实例538  使用PBE加密
    String algorithm = "PBEWithMD5AndDES";

    String saltFile = "saltData.dat";
    String dataFile = "fileData.dat";

    /**
     * 获取盐值
     *
     * @return
     * @throws Exception
     */
    public void initSalt() {
        byte[] salt = new byte[8];
        Random random = new Random();
        //生成随机数
        random.nextBytes(salt);
        //保存盐值
        writeFile(salt, saltFile);
    }

    /**
     * 获取钥匙
     *
     * @param password
     * @return
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeySpecException
     */
    private Key toKey(String password) throws NoSuchAlgorithmException,
            InvalidKeySpecException {
        PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algorithm);
        SecretKey secretKey = keyFactory.generateSecret(keySpec);
        return secretKey;
    }

    /**
     * 加密
     *
     * @param data
     * @param password
     * @throws InvalidKeySpecException
     * @throws NoSuchAlgorithmException
     * @throws NoSuchPaddingException
     * @throws InvalidAlgorithmParameterException
     * @throws InvalidKeyException
     * @throws BadPaddingException
     * @throws IllegalBlockSizeException
     */
    public void encrypt(byte[] data, String password)
            throws NoSuchAlgorithmException, InvalidKeySpecException,
            NoSuchPaddingException, InvalidKeyException,
            InvalidAlgorithmParameterException, IllegalBlockSizeException,
            BadPaddingException {
        Key key = toKey(password);
        byte[] salt = readFile(saltFile);
        PBEParameterSpec paramSpec = new PBEParameterSpec(salt, 100);
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
        writeFile(cipher.doFinal(data), dataFile);

    }

    /**
     * 解密
     *
     * @param data
     * @param password
     * @return
     * @throws InvalidKeySpecException
     * @throws NoSuchAlgorithmException
     * @throws NoSuchPaddingException
     * @throws InvalidAlgorithmParameterException
     * @throws InvalidKeyException
     * @throws BadPaddingException
     * @throws IllegalBlockSizeException
     */
    public String decrypt(String password) throws NoSuchAlgorithmException,
            InvalidKeySpecException, NoSuchPaddingException,
            InvalidKeyException, InvalidAlgorithmParameterException,
            IllegalBlockSizeException, BadPaddingException {
        Key key = toKey(password);
        byte[] salt = readFile(saltFile);
        byte[] data = readFile(dataFile);
        PBEParameterSpec paramSpec = new PBEParameterSpec(salt, 100);
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
        return new String(cipher.doFinal(data));
    }

    /**
     * 把数据写到指定的文件上
     *
     * @param data
     *            数据
     * @param fileName
     *            文件名称
     */
    public void writeFile(byte[] data, String fileName) {
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(fileName);
            fileOutputStream.write(data);
            fileOutputStream.close();
        } catch (FileNotFoundException e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 根据fileName读取数据文件
     *
     * @param fileName
     * @return
     */
    public byte[] readFile(String fileName) {

        // 读取
        try {
            File file = new File(fileName);
            FileInputStream fileInputStream = new FileInputStream(file);
            byte[] data = new byte[(int) file.length()];
            fileInputStream.read(data);
            fileInputStream.close();
            return data;
        } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;

    }

    public static void main(String[] avg) {
        BothPBEFile bothPBEFile = new BothPBEFile();
        String data = "明日科技";
        String password = "123456";
        System.out.println("加密前:" + data);
        try {
            bothPBEFile.initSalt();
            bothPBEFile.encrypt(data.getBytes(), password);
            String tdata = bothPBEFile.decrypt(password);
            System.out.println("解密后:" + tdata);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

实例539  使用PBE解密
    String algorithm = "PBEWithMD5AndDES";

    String saltFile = "saltData.dat";
    String dataFile = "fileData.dat";

    /**
     * 获取盐值
     *
     * @return
     * @throws Exception
     */
    public void initSalt() {
        byte[] salt = new byte[8];
        Random random = new Random();
        //生成随机数
        random.nextBytes(salt);
        //保存盐值
        writeFile(salt, saltFile);
    }

    /**
     * 获取钥匙
     *
     * @param password
     * @return
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeySpecException
     */
    private Key toKey(String password) throws NoSuchAlgorithmException,
            InvalidKeySpecException {
        PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algorithm);
        SecretKey secretKey = keyFactory.generateSecret(keySpec);
        return secretKey;
    }

    /**
     * 加密
     *
     * @param data
     * @param password
     * @throws InvalidKeySpecException
     * @throws NoSuchAlgorithmException
     * @throws NoSuchPaddingException
     * @throws InvalidAlgorithmParameterException
     * @throws InvalidKeyException
     * @throws BadPaddingException
     * @throws IllegalBlockSizeException
     */
    public void encrypt(byte[] data, String password)
            throws NoSuchAlgorithmException, InvalidKeySpecException,
            NoSuchPaddingException, InvalidKeyException,
            InvalidAlgorithmParameterException, IllegalBlockSizeException,
            BadPaddingException {
        Key key = toKey(password);
        byte[] salt = readFile(saltFile);
        PBEParameterSpec paramSpec = new PBEParameterSpec(salt, 100);
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
        writeFile(cipher.doFinal(data), dataFile);

    }

    /**
     * 解密
     *
     * @param data
     * @param password
     * @return
     * @throws InvalidKeySpecException
     * @throws NoSuchAlgorithmException
     * @throws NoSuchPaddingException
     * @throws InvalidAlgorithmParameterException
     * @throws InvalidKeyException
     * @throws BadPaddingException
     * @throws IllegalBlockSizeException
     */
    public String decrypt(String password) throws NoSuchAlgorithmException,
            InvalidKeySpecException, NoSuchPaddingException,
            InvalidKeyException, InvalidAlgorithmParameterException,
            IllegalBlockSizeException, BadPaddingException {
        Key key = toKey(password);
        byte[] salt = readFile(saltFile);
        byte[] data = readFile(dataFile);
        PBEParameterSpec paramSpec = new PBEParameterSpec(salt, 100);
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
        return new String(cipher.doFinal(data));
    }

    /**
     * 把数据写到指定的文件上
     *
     * @param data
     *            数据
     * @param fileName
     *            文件名称
     */
    public void writeFile(byte[] data, String fileName) {
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(fileName);
            fileOutputStream.write(data);
            fileOutputStream.close();
        } catch (FileNotFoundException e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 根据fileName读取数据文件
     *
     * @param fileName
     * @return
     */
    public byte[] readFile(String fileName) {

        // 读取
        try {
            File file = new File(fileName);
            FileInputStream fileInputStream = new FileInputStream(file);
            byte[] data = new byte[(int) file.length()];
            fileInputStream.read(data);
            fileInputStream.close();
            return data;
        } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;

    }

    public static void main(String[] avg) {
        BothPBEFile bothPBEFile = new BothPBEFile();
        String data = "明日科技";
        String password = "123456";
        System.out.println("加密前:" + data);
        try {
            bothPBEFile.initSalt();
            bothPBEFile.encrypt(data.getBytes(), password);
            String tdata = bothPBEFile.decrypt(password);
            System.out.println("解密后:" + tdata);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

20.2  Java非对称加密
实例540  生成RSA密钥对
BothRSAClientFile.java
    private String keyAlgorithm = "RSA";
    private String singAlgorithm = "MD5withRSA";
    // 服务端数据文件
    private String serverdataFile = "fileServerData.dat";
    // 客户端数据文件
    private String clientdataFile = "fileClientData.dat";
    // 签名文件
    private String signdataFile = "fileSignData.dat";
    // 公钥文件
    private String publickeyFile = "keyPublicData.dat";

    /**
     * 把数据写到指定的文件上
     *
     * @param data
     *            数据
     * @param fileName
     *            文件名称
     */
    public void writeFile(byte[] data, String fileName) {
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(fileName);
            fileOutputStream.write(data);
            fileOutputStream.close();
        } catch (FileNotFoundException e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 根据fileName读取数据文件
     *
     * @param fileName
     * @return
     */
    public byte[] readFile(String fileName) {

        // 读取
        try {
            File file = new File(fileName);
            FileInputStream fileInputStream = new FileInputStream(file);
            byte[] data = new byte[(int) file.length()];
            fileInputStream.read(data);
            fileInputStream.close();
            return data;
        } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;

    }

    /**
     * 校验数字签名
     *
     * @return 校验成功返回true 失败返回false
     */
    public boolean verifySign() {
        byte[] data = readFile(serverdataFile);
        byte[] publicKey = readFile(publickeyFile);
        byte[] sign = readFile(signdataFile);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey);
        KeyFactory keyFactory = null;
        PublicKey pubKey = null;
        try {
            keyFactory = KeyFactory.getInstance(keyAlgorithm);
            pubKey = keyFactory.generatePublic(keySpec);
        } catch (InvalidKeySpecException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        try {
            // 验证签名是否正常
            Signature signature = Signature.getInstance(singAlgorithm);
            signature.initVerify(pubKey);
            signature.update(data);
            return signature.verify(sign);
        } catch (SignatureException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 用公钥解密
     *
     * @return
     */
    public byte[] decryptByPublicKey() {
        byte[] data = readFile(serverdataFile);
        byte[] key = readFile(publickeyFile);
        // 取得公钥
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key);
        KeyFactory keyFactory = null;
        Key publicKey = null;
        try {
            keyFactory = KeyFactory.getInstance(keyAlgorithm);
            publicKey = keyFactory.generatePublic(x509KeySpec);
        } catch (InvalidKeySpecException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // 对数据解密
        try {
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.DECRYPT_MODE, publicKey);
            return cipher.doFinal(data);
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (BadPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 用公钥加密
     */
    public void encryptByPublicKey(byte[] data) {
        byte[] key = readFile(publickeyFile);
        // 取得公钥
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key);
        KeyFactory keyFactory = null;
        Key publicKey = null;
        try {
            keyFactory = KeyFactory.getInstance(keyAlgorithm);
            publicKey = keyFactory.generatePublic(x509KeySpec);
        } catch (InvalidKeySpecException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // 对数据加密
        try {
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            writeFile(cipher.doFinal(data), clientdataFile);
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (NoSuchPaddingException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (BadPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    public static void main(String[] arg) {
        BothRSAClientFile bothRSAClientFile = new BothRSAClientFile();
        BothRSAServerFile bothRSAServerFile = new BothRSAServerFile();

        String cdata = "服务端你好,这里是客户端";
        bothRSAClientFile.encryptByPublicKey(cdata.getBytes());
        byte [] cdata1 = bothRSAServerFile.decryptByPrivateKey();
        System.out.println("Client原始数据:"+cdata);
        System.out.println("Servet解密数据:"+new String (cdata1));
        
    }
BothRSAServerFile.java
    private String keyAlgorithm = "RSA";
    private String singAlgorithm = "MD5withRSA";
    // 服务端数据文件
    private String serverdataFile = "fileServerData.dat";
    // 客户端数据文件
    private String clientdataFile = "fileClientData.dat";
    // 签名文件
    private String signdataFile = "fileSignData.dat";
    // 私钥文件
    private String privatekeyFile = "keyPrivateData.dat";
    // 公钥文件
    private String publickeyFile = "keyPublicData.dat";

    /**
     * 把数据写到指定的文件上
     *
     * @param data
     *            数据
     * @param fileName
     *            文件名称
     */
    public void writeFile(byte[] data, String fileName) {
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(fileName);
            fileOutputStream.write(data);
            fileOutputStream.close();
        } catch (FileNotFoundException e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 根据fileName读取数据文件
     *
     * @param fileName
     * @return
     */
    public byte[] readFile(String fileName) {

        // 读取
        try {
            File file = new File(fileName);
            FileInputStream fileInputStream = new FileInputStream(file);
            byte[] data = new byte[(int) file.length()];
            fileInputStream.read(data);
            fileInputStream.close();
            return data;
        } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;

    }

    /**
     * 生成密钥对
     */
    public void generateKeyFile() {
        KeyPairGenerator keyPairGen = null;
        try {
            keyPairGen = KeyPairGenerator.getInstance(keyAlgorithm);
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        KeyPair keyPair = keyPairGen.generateKeyPair();

        // 公钥
        PublicKey publicKey = keyPair.getPublic();
        writeFile(publicKey.getEncoded(), publickeyFile);

        // 私钥
        PrivateKey privateKey = keyPair.getPrivate();
        writeFile(privateKey.getEncoded(), privatekeyFile);
    }

    /**
     * 用私钥加密
     *
     * @param data
     * @return
     */
    public void encryptByPrivateKey(byte[] data) {

        // 取得私钥
        byte[] key = readFile(privatekeyFile);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(key);
        KeyFactory keyFactory = null;
        Key privateKey = null;
        try {
            keyFactory = KeyFactory.getInstance(keyAlgorithm);
            privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
        } catch (InvalidKeySpecException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // 对数据加密
        try {
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.ENCRYPT_MODE, privateKey);
            writeFile(cipher.doFinal(data), serverdataFile);
        } catch (IllegalBlockSizeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (BadPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 用私钥对信息生成数字签名
     *
     * @param data
     *            加密数据
     * @param privateKey
     *            私钥
     *
     * @return
     * @throws Exception
     */
    public void generateSign() {

        byte[] privateKey = readFile(privatekeyFile);
        byte[] serverData = readFile(serverdataFile);
        // 构造PKCS8EncodedKeySpec对象
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(privateKey);

        // KEY_ALGORITHM 指定的加密算法
        KeyFactory keyFactory = null;
        PrivateKey priKey = null;
        try {
            //生成私钥
            keyFactory = KeyFactory.getInstance(keyAlgorithm);
            priKey = keyFactory.generatePrivate(pkcs8KeySpec);
        } catch (InvalidKeySpecException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        try {
            //生成数字签名
            Signature signature = Signature.getInstance(singAlgorithm);
            signature.initSign(priKey);
            signature.update(serverData);
            writeFile(signature.sign(), signdataFile);
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SignatureException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 用私钥解密
     *
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public byte[] decryptByPrivateKey() {
        byte[] data = readFile(clientdataFile);
        byte[] key = readFile(privatekeyFile);
        // 取得私钥
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(key);
        KeyFactory keyFactory = null;
        Key privateKey = null;
        try {
            keyFactory = KeyFactory.getInstance(keyAlgorithm);
            privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
        } catch (InvalidKeySpecException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        try {
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            return cipher.doFinal(data);
        } catch (IllegalBlockSizeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (BadPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] arg) {
        String data = "客户端你好,我是服务端";
        // 服务端操作
        BothRSAServerFile bothRSAServerFile = new BothRSAServerFile();
        // 生成密钥对
        bothRSAServerFile.generateKeyFile();
        // 加密明文
        bothRSAServerFile.encryptByPrivateKey(data.getBytes());
        // 生成签名
        bothRSAServerFile.generateSign();

        // 客户端操作
        BothRSAClientFile bothRSAClientFile = new BothRSAClientFile();

        byte[]  data1 =null;
        if(bothRSAClientFile.verifySign()){
            data1= bothRSAClientFile.decryptByPublicKey();
        }
        System.out.println("Servet原始数据:"+data);
        System.out.println("Client解密数据:"+new String (data1));
        
    }

实例541  使用RSA的签名
BothRSAClientFile.java
    private String keyAlgorithm = "RSA";
    private String singAlgorithm = "MD5withRSA";
    // 服务端数据文件
    private String serverdataFile = "fileServerData.dat";
    // 客户端数据文件
    private String clientdataFile = "fileClientData.dat";
    // 签名文件
    private String signdataFile = "fileSignData.dat";
    // 公钥文件
    private String publickeyFile = "keyPublicData.dat";

    /**
     * 把数据写到指定的文件上
     *
     * @param data
     *            数据
     * @param fileName
     *            文件名称
     */
    public void writeFile(byte[] data, String fileName) {
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(fileName);
            fileOutputStream.write(data);
            fileOutputStream.close();
        } catch (FileNotFoundException e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 根据fileName读取数据文件
     *
     * @param fileName
     * @return
     */
    public byte[] readFile(String fileName) {

        // 读取
        try {
            File file = new File(fileName);
            FileInputStream fileInputStream = new FileInputStream(file);
            byte[] data = new byte[(int) file.length()];
            fileInputStream.read(data);
            fileInputStream.close();
            return data;
        } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;

    }

    /**
     * 校验数字签名
     *
     * @return 校验成功返回true 失败返回false
     */
    public boolean verifySign() {
        byte[] data = readFile(serverdataFile);
        byte[] publicKey = readFile(publickeyFile);
        byte[] sign = readFile(signdataFile);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey);
        KeyFactory keyFactory = null;
        PublicKey pubKey = null;
        try {
            keyFactory = KeyFactory.getInstance(keyAlgorithm);
            pubKey = keyFactory.generatePublic(keySpec);
        } catch (InvalidKeySpecException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        try {
            // 验证签名是否正常
            Signature signature = Signature.getInstance(singAlgorithm);
            signature.initVerify(pubKey);
            signature.update(data);
            return signature.verify(sign);
        } catch (SignatureException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 用公钥解密
     *
     * @return
     */
    public byte[] decryptByPublicKey() {
        byte[] data = readFile(serverdataFile);
        byte[] key = readFile(publickeyFile);
        // 取得公钥
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key);
        KeyFactory keyFactory = null;
        Key publicKey = null;
        try {
            keyFactory = KeyFactory.getInstance(keyAlgorithm);
            publicKey = keyFactory.generatePublic(x509KeySpec);
        } catch (InvalidKeySpecException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // 对数据解密
        try {
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.DECRYPT_MODE, publicKey);
            return cipher.doFinal(data);
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (BadPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 用公钥加密
     */
    public void encryptByPublicKey(byte[] data) {
        byte[] key = readFile(publickeyFile);
        // 取得公钥
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key);
        KeyFactory keyFactory = null;
        Key publicKey = null;
        try {
            keyFactory = KeyFactory.getInstance(keyAlgorithm);
            publicKey = keyFactory.generatePublic(x509KeySpec);
        } catch (InvalidKeySpecException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // 对数据加密
        try {
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            writeFile(cipher.doFinal(data), clientdataFile);
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (NoSuchPaddingException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (BadPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    public static void main(String[] arg) {
        BothRSAClientFile bothRSAClientFile = new BothRSAClientFile();
        BothRSAServerFile bothRSAServerFile = new BothRSAServerFile();

        String cdata = "服务端你好,这里是客户端";
        bothRSAClientFile.encryptByPublicKey(cdata.getBytes());
        byte [] cdata1 = bothRSAServerFile.decryptByPrivateKey();
        System.out.println("Client原始数据:"+cdata);
        System.out.println("Servet解密数据:"+new String (cdata1));
        
    }
BothRSAServerFile.java
    private String keyAlgorithm = "RSA";
    private String singAlgorithm = "MD5withRSA";
    // 服务端数据文件
    private String serverdataFile = "fileServerData.dat";
    // 客户端数据文件
    private String clientdataFile = "fileClientData.dat";
    // 签名文件
    private String signdataFile = "fileSignData.dat";
    // 私钥文件
    private String privatekeyFile = "keyPrivateData.dat";
    // 公钥文件
    private String publickeyFile = "keyPublicData.dat";

    /**
     * 把数据写到指定的文件上
     *
     * @param data
     *            数据
     * @param fileName
     *            文件名称
     */
    public void writeFile(byte[] data, String fileName) {
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(fileName);
            fileOutputStream.write(data);
            fileOutputStream.close();
        } catch (FileNotFoundException e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 根据fileName读取数据文件
     *
     * @param fileName
     * @return
     */
    public byte[] readFile(String fileName) {

        // 读取
        try {
            File file = new File(fileName);
            FileInputStream fileInputStream = new FileInputStream(file);
            byte[] data = new byte[(int) file.length()];
            fileInputStream.read(data);
            fileInputStream.close();
            return data;
        } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;

    }

    /**
     * 生成密钥对
     */
    public void generateKeyFile() {
        KeyPairGenerator keyPairGen = null;
        try {
            keyPairGen = KeyPairGenerator.getInstance(keyAlgorithm);
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        KeyPair keyPair = keyPairGen.generateKeyPair();

        // 公钥
        PublicKey publicKey = keyPair.getPublic();
        writeFile(publicKey.getEncoded(), publickeyFile);

        // 私钥
        PrivateKey privateKey = keyPair.getPrivate();
        writeFile(privateKey.getEncoded(), privatekeyFile);
    }

    /**
     * 用私钥加密
     *
     * @param data
     * @return
     */
    public void encryptByPrivateKey(byte[] data) {

        // 取得私钥
        byte[] key = readFile(privatekeyFile);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(key);
        KeyFactory keyFactory = null;
        Key privateKey = null;
        try {
            keyFactory = KeyFactory.getInstance(keyAlgorithm);
            privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
        } catch (InvalidKeySpecException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // 对数据加密
        try {
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.ENCRYPT_MODE, privateKey);
            writeFile(cipher.doFinal(data), serverdataFile);
        } catch (IllegalBlockSizeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (BadPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 用私钥对信息生成数字签名
     *
     * @param data
     *            加密数据
     * @param privateKey
     *            私钥
     *
     * @return
     * @throws Exception
     */
    public void generateSign() {

        byte[] privateKey = readFile(privatekeyFile);
        byte[] serverData = readFile(serverdataFile);
        // 构造PKCS8EncodedKeySpec对象
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(privateKey);

        // KEY_ALGORITHM 指定的加密算法
        KeyFactory keyFactory = null;
        PrivateKey priKey = null;
        try {
            keyFactory = KeyFactory.getInstance(keyAlgorithm);
            priKey = keyFactory.generatePrivate(pkcs8KeySpec);
        } catch (InvalidKeySpecException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        try {
            Signature signature = Signature.getInstance(singAlgorithm);
            signature.initSign(priKey);
            signature.update(serverData);
            writeFile(signature.sign(), signdataFile);
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SignatureException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 用私钥解密
     *
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public byte[] decryptByPrivateKey() {
        byte[] data = readFile(clientdataFile);
        byte[] key = readFile(privatekeyFile);
        // 取得私钥
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(key);
        KeyFactory keyFactory = null;
        Key privateKey = null;
        try {
            keyFactory = KeyFactory.getInstance(keyAlgorithm);
            privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
        } catch (InvalidKeySpecException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        try {
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            return cipher.doFinal(data);
        } catch (IllegalBlockSizeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (BadPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] arg) {
        String data = "客户端你好,我是服务端";
        // 服务端操作
        BothRSAServerFile bothRSAServerFile = new BothRSAServerFile();
        // 生成密钥对
        bothRSAServerFile.generateKeyFile();
        // 加密明文
        bothRSAServerFile.encryptByPrivateKey(data.getBytes());
        // 生成签名
        bothRSAServerFile.generateSign();

        // 客户端操作
        BothRSAClientFile bothRSAClientFile = new BothRSAClientFile();

        byte[]  data1 =null;
        if(bothRSAClientFile.verifySign()){
            data1= bothRSAClientFile.decryptByPublicKey();
        }
        System.out.println("Servet原始数据:"+data);
        System.out.println("Client解密数据:"+new String (data1));    
    }

实例542  RSA服务端加密
BothRSAClientFile.java
    private String keyAlgorithm = "RSA";
    private String singAlgorithm = "MD5withRSA";
    // 服务端数据文件
    private String serverdataFile = "fileServerData.dat";
    // 客户端数据文件
    private String clientdataFile = "fileClientData.dat";
    // 签名文件
    private String signdataFile = "fileSignData.dat";
    // 公钥文件
    private String publickeyFile = "keyPublicData.dat";

    /**
     * 把数据写到指定的文件上
     *
     * @param data
     *            数据
     * @param fileName
     *            文件名称
     */
    public void writeFile(byte[] data, String fileName) {
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(fileName);
            fileOutputStream.write(data);
            fileOutputStream.close();
        } catch (FileNotFoundException e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 根据fileName读取数据文件
     *
     * @param fileName
     * @return
     */
    public byte[] readFile(String fileName) {

        // 读取
        try {
            File file = new File(fileName);
            FileInputStream fileInputStream = new FileInputStream(file);
            byte[] data = new byte[(int) file.length()];
            fileInputStream.read(data);
            fileInputStream.close();
            return data;
        } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;

    }

    /**
     * 校验数字签名
     *
     * @return 校验成功返回true 失败返回false
     */
    public boolean verifySign() {
        byte[] data = readFile(serverdataFile);
        byte[] publicKey = readFile(publickeyFile);
        byte[] sign = readFile(signdataFile);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey);
        KeyFactory keyFactory = null;
        PublicKey pubKey = null;
        try {
            keyFactory = KeyFactory.getInstance(keyAlgorithm);
            pubKey = keyFactory.generatePublic(keySpec);
        } catch (InvalidKeySpecException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        try {
            // 验证签名是否正常
            Signature signature = Signature.getInstance(singAlgorithm);
            signature.initVerify(pubKey);
            signature.update(data);
            return signature.verify(sign);
        } catch (SignatureException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 用公钥解密
     *
     * @return
     */
    public byte[] decryptByPublicKey() {
        byte[] data = readFile(serverdataFile);
        byte[] key = readFile(publickeyFile);
        // 取得公钥
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key);
        KeyFactory keyFactory = null;
        Key publicKey = null;
        try {
            keyFactory = KeyFactory.getInstance(keyAlgorithm);
            publicKey = keyFactory.generatePublic(x509KeySpec);
        } catch (InvalidKeySpecException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // 对数据解密
        try {
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.DECRYPT_MODE, publicKey);
            return cipher.doFinal(data);
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (BadPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 用公钥加密
     */
    public void encryptByPublicKey(byte[] data) {
        byte[] key = readFile(publickeyFile);
        // 取得公钥
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key);
        KeyFactory keyFactory = null;
        Key publicKey = null;
        try {
            keyFactory = KeyFactory.getInstance(keyAlgorithm);
            publicKey = keyFactory.generatePublic(x509KeySpec);
        } catch (InvalidKeySpecException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // 对数据加密
        try {
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            writeFile(cipher.doFinal(data), clientdataFile);
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (NoSuchPaddingException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (BadPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    public static void main(String[] arg) {
        BothRSAClientFile bothRSAClientFile = new BothRSAClientFile();
        BothRSAServerFile bothRSAServerFile = new BothRSAServerFile();

        String cdata = "服务端你好,这里是客户端";
        bothRSAClientFile.encryptByPublicKey(cdata.getBytes());
        byte [] cdata1 = bothRSAServerFile.decryptByPrivateKey();
        System.out.println("Client原始数据:"+cdata);
        System.out.println("Servet解密数据:"+new String (cdata1));
        
    }
BothRSAServerFile.java
    private String keyAlgorithm = "RSA";
    private String singAlgorithm = "MD5withRSA";
    // 服务端数据文件
    private String serverdataFile = "fileServerData.dat";
    // 客户端数据文件
    private String clientdataFile = "fileClientData.dat";
    // 签名文件
    private String signdataFile = "fileSignData.dat";
    // 私钥文件
    private String privatekeyFile = "keyPrivateData.dat";
    // 公钥文件
    private String publickeyFile = "keyPublicData.dat";

    /**
     * 把数据写到指定的文件上
     *
     * @param data
     *            数据
     * @param fileName
     *            文件名称
     */
    public void writeFile(byte[] data, String fileName) {
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(fileName);
            fileOutputStream.write(data);
            fileOutputStream.close();
        } catch (FileNotFoundException e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 根据fileName读取数据文件
     *
     * @param fileName
     * @return
     */
    public byte[] readFile(String fileName) {

        // 读取
        try {
            File file = new File(fileName);
            FileInputStream fileInputStream = new FileInputStream(file);
            byte[] data = new byte[(int) file.length()];
            fileInputStream.read(data);
            fileInputStream.close();
            return data;
        } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;

    }

    /**
     * 生成密钥对
     */
    public void generateKeyFile() {
        KeyPairGenerator keyPairGen = null;
        try {
            keyPairGen = KeyPairGenerator.getInstance(keyAlgorithm);
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        KeyPair keyPair = keyPairGen.generateKeyPair();

        // 公钥
        PublicKey publicKey = keyPair.getPublic();
        writeFile(publicKey.getEncoded(), publickeyFile);

        // 私钥
        PrivateKey privateKey = keyPair.getPrivate();
        writeFile(privateKey.getEncoded(), privatekeyFile);
    }

    /**
     * 用私钥加密
     *
     * @param data
     * @return
     */
    public void encryptByPrivateKey(byte[] data) {

        // 取得私钥
        byte[] key = readFile(privatekeyFile);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(key);
        KeyFactory keyFactory = null;
        Key privateKey = null;
        try {
            keyFactory = KeyFactory.getInstance(keyAlgorithm);
            privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
        } catch (InvalidKeySpecException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // 对数据加密
        try {
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.ENCRYPT_MODE, privateKey);
            writeFile(cipher.doFinal(data), serverdataFile);
        } catch (IllegalBlockSizeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (BadPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 用私钥对信息生成数字签名
     *
     * @param data
     *            加密数据
     * @param privateKey
     *            私钥
     *
     * @return
     * @throws Exception
     */
    public void generateSign() {

        byte[] privateKey = readFile(privatekeyFile);
        byte[] serverData = readFile(serverdataFile);
        // 构造PKCS8EncodedKeySpec对象
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(privateKey);

        // KEY_ALGORITHM 指定的加密算法
        KeyFactory keyFactory = null;
        PrivateKey priKey = null;
        try {
            keyFactory = KeyFactory.getInstance(keyAlgorithm);
            priKey = keyFactory.generatePrivate(pkcs8KeySpec);
        } catch (InvalidKeySpecException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        try {
            Signature signature = Signature.getInstance(singAlgorithm);
            signature.initSign(priKey);
            signature.update(serverData);
            writeFile(signature.sign(), signdataFile);
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SignatureException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 用私钥解密
     *
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public byte[] decryptByPrivateKey() {
        byte[] data = readFile(clientdataFile);
        byte[] key = readFile(privatekeyFile);
        // 取得私钥
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(key);
        KeyFactory keyFactory = null;
        Key privateKey = null;
        try {
            keyFactory = KeyFactory.getInstance(keyAlgorithm);
            privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
        } catch (InvalidKeySpecException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        try {
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            return cipher.doFinal(data);
        } catch (IllegalBlockSizeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (BadPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] arg) {
        String data = "客户端你好,我是服务端";
        // 服务端操作
        BothRSAServerFile bothRSAServerFile = new BothRSAServerFile();
        // 生成密钥对
        bothRSAServerFile.generateKeyFile();
        // 加密明文
        bothRSAServerFile.encryptByPrivateKey(data.getBytes());
        // 生成签名
        bothRSAServerFile.generateSign();

        // 客户端操作
        BothRSAClientFile bothRSAClientFile = new BothRSAClientFile();

        byte[]  data1 =null;
        if(bothRSAClientFile.verifySign()){
            data1= bothRSAClientFile.decryptByPublicKey();
        }
        System.out.println("Servet原始数据:"+data);
        System.out.println("Client解密数据:"+new String (data1));
        
    }

实例543  RSA客户端加密
BothRSAClientFile.java
    private String keyAlgorithm = "RSA";
    private String singAlgorithm = "MD5withRSA";
    // 服务端数据文件
    private String serverdataFile = "fileServerData.dat";
    // 客户端数据文件
    private String clientdataFile = "fileClientData.dat";
    // 签名文件
    private String signdataFile = "fileSignData.dat";
    // 公钥文件
    private String publickeyFile = "keyPublicData.dat";

    /**
     * 把数据写到指定的文件上
     *
     * @param data
     *            数据
     * @param fileName
     *            文件名称
     */
    public void writeFile(byte[] data, String fileName) {
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(fileName);
            fileOutputStream.write(data);
            fileOutputStream.close();
        } catch (FileNotFoundException e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 根据fileName读取数据文件
     *
     * @param fileName
     * @return
     */
    public byte[] readFile(String fileName) {

        // 读取
        try {
            File file = new File(fileName);
            FileInputStream fileInputStream = new FileInputStream(file);
            byte[] data = new byte[(int) file.length()];
            fileInputStream.read(data);
            fileInputStream.close();
            return data;
        } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;

    }

    /**
     * 校验数字签名
     *
     * @return 校验成功返回true 失败返回false
     */
    public boolean verifySign() {
        byte[] data = readFile(serverdataFile);
        byte[] publicKey = readFile(publickeyFile);
        byte[] sign = readFile(signdataFile);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey);
        KeyFactory keyFactory = null;
        PublicKey pubKey = null;
        try {
            keyFactory = KeyFactory.getInstance(keyAlgorithm);
            pubKey = keyFactory.generatePublic(keySpec);
        } catch (InvalidKeySpecException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        try {
            // 验证签名是否正常
            Signature signature = Signature.getInstance(singAlgorithm);
            signature.initVerify(pubKey);
            signature.update(data);
            return signature.verify(sign);
        } catch (SignatureException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 用公钥解密
     *
     * @return
     */
    public byte[] decryptByPublicKey() {
        byte[] data = readFile(serverdataFile);
        byte[] key = readFile(publickeyFile);
        // 取得公钥
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key);
        KeyFactory keyFactory = null;
        Key publicKey = null;
        try {
            keyFactory = KeyFactory.getInstance(keyAlgorithm);
            publicKey = keyFactory.generatePublic(x509KeySpec);
        } catch (InvalidKeySpecException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // 对数据解密
        try {
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.DECRYPT_MODE, publicKey);
            return cipher.doFinal(data);
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (BadPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 用公钥加密
     */
    public void encryptByPublicKey(byte[] data) {
        byte[] key = readFile(publickeyFile);
        // 取得公钥
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key);
        KeyFactory keyFactory = null;
        Key publicKey = null;
        try {
            keyFactory = KeyFactory.getInstance(keyAlgorithm);
            publicKey = keyFactory.generatePublic(x509KeySpec);
        } catch (InvalidKeySpecException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // 对数据加密
        try {
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            writeFile(cipher.doFinal(data), clientdataFile);
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (NoSuchPaddingException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (BadPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    public static void main(String[] arg) {
        BothRSAClientFile bothRSAClientFile = new BothRSAClientFile();
        BothRSAServerFile bothRSAServerFile = new BothRSAServerFile();

        String cdata = "服务端你好,这里是客户端";
        bothRSAClientFile.encryptByPublicKey(cdata.getBytes());
        byte [] cdata1 = bothRSAServerFile.decryptByPrivateKey();
        System.out.println("Client原始数据:"+cdata);
        System.out.println("Servet解密数据:"+new String (cdata1));
        
    }
BothRSAServerFile.java
    private String keyAlgorithm = "RSA";
    private String singAlgorithm = "MD5withRSA";
    // 服务端数据文件
    private String serverdataFile = "fileServerData.dat";
    // 客户端数据文件
    private String clientdataFile = "fileClientData.dat";
    // 签名文件
    private String signdataFile = "fileSignData.dat";
    // 私钥文件
    private String privatekeyFile = "keyPrivateData.dat";
    // 公钥文件
    private String publickeyFile = "keyPublicData.dat";

    /**
     * 把数据写到指定的文件上
     *
     * @param data
     *            数据
     * @param fileName
     *            文件名称
     */
    public void writeFile(byte[] data, String fileName) {
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(fileName);
            fileOutputStream.write(data);
            fileOutputStream.close();
        } catch (FileNotFoundException e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 根据fileName读取数据文件
     *
     * @param fileName
     * @return
     */
    public byte[] readFile(String fileName) {

        // 读取
        try {
            File file = new File(fileName);
            FileInputStream fileInputStream = new FileInputStream(file);
            byte[] data = new byte[(int) file.length()];
            fileInputStream.read(data);
            fileInputStream.close();
            return data;
        } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;

    }

    /**
     * 生成密钥对
     */
    public void generateKeyFile() {
        KeyPairGenerator keyPairGen = null;
        try {
            keyPairGen = KeyPairGenerator.getInstance(keyAlgorithm);
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        KeyPair keyPair = keyPairGen.generateKeyPair();

        // 公钥
        PublicKey publicKey = keyPair.getPublic();
        writeFile(publicKey.getEncoded(), publickeyFile);

        // 私钥
        PrivateKey privateKey = keyPair.getPrivate();
        writeFile(privateKey.getEncoded(), privatekeyFile);
    }

    /**
     * 用私钥加密
     *
     * @param data
     * @return
     */
    public void encryptByPrivateKey(byte[] data) {

        // 取得私钥
        byte[] key = readFile(privatekeyFile);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(key);
        KeyFactory keyFactory = null;
        Key privateKey = null;
        try {
            keyFactory = KeyFactory.getInstance(keyAlgorithm);
            privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
        } catch (InvalidKeySpecException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // 对数据加密
        try {
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.ENCRYPT_MODE, privateKey);
            writeFile(cipher.doFinal(data), serverdataFile);
        } catch (IllegalBlockSizeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (BadPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 用私钥对信息生成数字签名
     *
     * @param data
     *            加密数据
     * @param privateKey
     *            私钥
     *
     * @return
     * @throws Exception
     */
    public void generateSign() {

        byte[] privateKey = readFile(privatekeyFile);
        byte[] serverData = readFile(serverdataFile);
        // 构造PKCS8EncodedKeySpec对象
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(privateKey);

        // KEY_ALGORITHM 指定的加密算法
        KeyFactory keyFactory = null;
        PrivateKey priKey = null;
        try {
            keyFactory = KeyFactory.getInstance(keyAlgorithm);
            priKey = keyFactory.generatePrivate(pkcs8KeySpec);
        } catch (InvalidKeySpecException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        try {
            Signature signature = Signature.getInstance(singAlgorithm);
            signature.initSign(priKey);
            signature.update(serverData);
            writeFile(signature.sign(), signdataFile);
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SignatureException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 用私钥解密
     *
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public byte[] decryptByPrivateKey() {
        byte[] data = readFile(clientdataFile);
        byte[] key = readFile(privatekeyFile);
        // 取得私钥
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(key);
        KeyFactory keyFactory = null;
        Key privateKey = null;
        try {
            keyFactory = KeyFactory.getInstance(keyAlgorithm);
            privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
        } catch (InvalidKeySpecException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        try {
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            return cipher.doFinal(data);
        } catch (IllegalBlockSizeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (BadPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] arg) {
        String data = "客户端你好,我是服务端";
        // 服务端操作
        BothRSAServerFile bothRSAServerFile = new BothRSAServerFile();
        // 生成密钥对
        bothRSAServerFile.generateKeyFile();
        // 加密明文
        bothRSAServerFile.encryptByPrivateKey(data.getBytes());
        // 生成签名
        bothRSAServerFile.generateSign();

        // 客户端操作
        BothRSAClientFile bothRSAClientFile = new BothRSAClientFile();

        byte[]  data1 =null;
        if(bothRSAClientFile.verifySign()){
            data1= bothRSAClientFile.decryptByPublicKey();
        }
        System.out.println("Servet原始数据:"+data);
        System.out.println("Client解密数据:"+new String (data1));
        
    }

实例544  DH服务端加密
BothDHClientFile.java
    private String keyAlgorithm = "DH";
    private String secretAlgorithm = "DES";
    // 服务端数据文件
    private String serverdataFile = "fileServerData.dat";
    // 客户端数据文件
    private String clientdataFile = "fileClientData.dat";
    // 服务端公钥文件
    private String publicServerkeyFile = "keyServerPublicData.dat";
    // 客户端公钥文件
    private String publicClientkeyFile = "keyClientPublicData.dat";
    // 客户端私钥文件
    private String privateClientkeyFile = "keyClientPrivateData.dat";

    /**
     * 把数据写到指定的文件上
     *
     * @param data
     *            数据
     * @param fileName
     *            文件名称
     */
    public void writeFile(byte[] data, String fileName) {
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(fileName);
            fileOutputStream.write(data);
            fileOutputStream.close();
        } catch (FileNotFoundException e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 根据fileName读取数据文件
     *
     * @param fileName
     * @return
     */
    public byte[] readFile(String fileName) {

        // 读取
        try {
            File file = new File(fileName);
            FileInputStream fileInputStream = new FileInputStream(file);
            byte[] data = new byte[(int) file.length()];
            fileInputStream.read(data);
            fileInputStream.close();
            return data;
        } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;

    }

    /**
     * 生成客户端密钥对
     */
    public void generateClientKeyFile() {
        KeyPairGenerator keyPairGen = null;

        try {
            byte[] publicServerkey = readFile(publicServerkeyFile);
            X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(
                    publicServerkey);
            KeyFactory keyFactory = KeyFactory.getInstance(keyAlgorithm);
            PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
            DHParameterSpec dhParameterSpec = ((DHPublicKey) publicKey)
                    .getParams();

            keyPairGen = KeyPairGenerator
                    .getInstance(keyFactory.getAlgorithm());
            keyPairGen.initialize(dhParameterSpec);

        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvalidAlgorithmParameterException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        KeyPair keyPair = keyPairGen.generateKeyPair();

        // 公钥
        PublicKey publicKey = keyPair.getPublic();
        writeFile(publicKey.getEncoded(), publicClientkeyFile);

        // 私钥
        PrivateKey privateKey = keyPair.getPrivate();
        writeFile(privateKey.getEncoded(), privateClientkeyFile);
    }

    /**
     * 生成客户端机密密钥
     *
     * @return
     */
    private SecretKey getClientSecretKey() {
        byte[] privateClientKey = readFile(privateClientkeyFile);
        byte[] publicServerKey = readFile(publicServerkeyFile);

        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(publicServerKey);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(
                privateClientKey);

        PublicKey publicKey = null;
        KeyFactory keyFactory = null;
        Key privateKey = null;
        KeyAgreement keyAgree = null;

        try {
            keyFactory = KeyFactory.getInstance(keyAlgorithm);
            publicKey = keyFactory.generatePublic(x509KeySpec);
            // privateKey = keyFactory.generatePrivate(x509KeySpec);
            privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
            // 创建密钥协议
            keyAgree = KeyAgreement.getInstance(keyFactory.getAlgorithm());
            keyAgree.init(privateKey);
            keyAgree.doPhase(publicKey, true);
            return keyAgree.generateSecret(secretAlgorithm);
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 客户端数据解密
     *
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public byte[] decryptForClient() {
        SecretKey secretKey = getClientSecretKey();

        try {
            byte[] data = readFile(serverdataFile);
            Cipher cipher = Cipher.getInstance(secretKey.getAlgorithm());
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            return cipher.doFinal(data);
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (BadPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 客户端数据加密
     *
     * @param data
     */
    public void encryptForClient(byte[] data) {

        SecretKey secretKey = getClientSecretKey();

        try {
            Cipher cipher = Cipher.getInstance(secretKey.getAlgorithm());
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            writeFile(cipher.doFinal(data), clientdataFile);
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (BadPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static void main(String[] arg) {
        String data = "服务端你好,我是客户端";
        BothDHServerFile bothDHServerFile = new BothDHServerFile();
        BothDHClientFile bothDHClientFile = new BothDHClientFile();

        // 生成服务端密钥对
        bothDHServerFile.generateServerKeyFile();
        // 生成客户端密钥对
        bothDHClientFile.generateClientKeyFile();
        // 客户端加密
        bothDHClientFile.encryptForClient(data.getBytes());
        // 服务端解密
        byte[] data1 = bothDHServerFile.decryptForServer();
        System.out.println("Client原始数据:" + data);
        System.out.println("Servet解密数据:" + new String(data1));

    }
BothDHServerFile.java
    private String keyAlgorithm = "DH";
    private String secretAlgorithm = "DES";
    // 服务端数据文件
    private String serverdataFile = "fileServerData.dat";
    // 客户端数据文件
    private String clientdataFile = "fileClientData.dat";
    // 服务端私钥文件
    private String privateServerkeyFile = "keyServerPrivateData.dat";
    // 服务端公钥文件
    private String publicServerkeyFile = "keyServerPublicData.dat";
    // 客户端公钥文件
    private String publicClientkeyFile = "keyClientPublicData.dat";

    /**
     * 把数据写到指定的文件上
     *
     * @param data
     *            数据
     * @param fileName
     *            文件名称
     */
    public void writeFile(byte[] data, String fileName) {
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(fileName);
            fileOutputStream.write(data);
            fileOutputStream.close();
        } catch (FileNotFoundException e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 根据fileName读取数据文件
     *
     * @param fileName
     * @return
     */
    public byte[] readFile(String fileName) {

        // 读取
        try {
            File file = new File(fileName);
            FileInputStream fileInputStream = new FileInputStream(file);
            byte[] data = new byte[(int) file.length()];
            fileInputStream.read(data);
            fileInputStream.close();
            return data;
        } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;

    }

    /**
     * 生成服务端密钥对
     */
    public void generateServerKeyFile() {
        KeyPairGenerator keyPairGen = null;
        try {
            keyPairGen = KeyPairGenerator.getInstance(keyAlgorithm);
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        KeyPair keyPair = keyPairGen.generateKeyPair();

        // 公钥
        PublicKey publicKey = keyPair.getPublic();
        writeFile(publicKey.getEncoded(), publicServerkeyFile);

        // 私钥
        PrivateKey privateKey = keyPair.getPrivate();
        writeFile(privateKey.getEncoded(), privateServerkeyFile);
    }

    /**
     * 生成服务端机密密钥
     *
     * @return
     */
    private SecretKey getServerSecretKey() {
        byte[] privateServerKey = readFile(privateServerkeyFile);
        byte[] publicClientKey = readFile(publicClientkeyFile);

        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(publicClientKey);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(
                privateServerKey);

        Key publicKey = null;
        KeyFactory keyFactory = null;
        Key privateKey = null;
        KeyAgreement keyAgree = null;

        try {
            keyFactory = KeyFactory.getInstance(keyAlgorithm);
            publicKey = keyFactory.generatePublic(x509KeySpec);
            privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
            // 创建密钥协议
            keyAgree = KeyAgreement.getInstance(keyFactory.getAlgorithm());
            //初始化密钥
            keyAgree.init(privateKey);
            keyAgree.doPhase(publicKey, true);
            return keyAgree.generateSecret(secretAlgorithm);
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 服务端数据加密
     *
     * @param data
     */
    public void encryptForServer(byte[] data) {

        SecretKey secretKey = getServerSecretKey();

        try {
            Cipher cipher = Cipher.getInstance(secretKey.getAlgorithm());
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            writeFile(cipher.doFinal(data), serverdataFile);
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (BadPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 服务端数据解密
     *
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public byte[] decryptForServer() {
        SecretKey secretKey = getServerSecretKey();

        try {
            byte[] data = readFile(clientdataFile);
            Cipher cipher = Cipher.getInstance(secretKey.getAlgorithm());
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            return cipher.doFinal(data);
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (BadPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] arg) {
        String data = "客户端你好,我是服务端";
        BothDHServerFile bothDHServerFile = new BothDHServerFile();
        BothDHClientFile bothDHClientFile = new BothDHClientFile();

        // 生成服务端密钥对
        bothDHServerFile.generateServerKeyFile();
        // 生成客户端密钥对
        bothDHClientFile.generateClientKeyFile();
        // 服务端加密
        bothDHServerFile.encryptForServer(data.getBytes());
        // 客户端解密
        byte[] data1 = bothDHClientFile.decryptForClient();
        System.out.println("Servet原始数据:" + data);
        System.out.println("Client解密数据:" + new String(data1));
    }

实例545  DH客户端加密
BothDHClientFile.java
    private String keyAlgorithm = "DH";
    private String secretAlgorithm = "DES";
    // 服务端数据文件
    private String serverdataFile = "fileServerData.dat";
    // 客户端数据文件
    private String clientdataFile = "fileClientData.dat";
    // 服务端公钥文件
    private String publicServerkeyFile = "keyServerPublicData.dat";
    // 客户端公钥文件
    private String publicClientkeyFile = "keyClientPublicData.dat";
    // 客户端私钥文件
    private String privateClientkeyFile = "keyClientPrivateData.dat";

    /**
     * 把数据写到指定的文件上
     *
     * @param data
     *            数据
     * @param fileName
     *            文件名称
     */
    public void writeFile(byte[] data, String fileName) {
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(fileName);
            fileOutputStream.write(data);
            fileOutputStream.close();
        } catch (FileNotFoundException e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 根据fileName读取数据文件
     *
     * @param fileName
     * @return
     */
    public byte[] readFile(String fileName) {

        // 读取
        try {
            File file = new File(fileName);
            FileInputStream fileInputStream = new FileInputStream(file);
            byte[] data = new byte[(int) file.length()];
            fileInputStream.read(data);
            fileInputStream.close();
            return data;
        } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;

    }

    /**
     * 生成客户端密钥对
     */
    public void generateClientKeyFile() {
        KeyPairGenerator keyPairGen = null;

        try {
            byte[] publicServerkey = readFile(publicServerkeyFile);
            X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(
                    publicServerkey);
            KeyFactory keyFactory = KeyFactory.getInstance(keyAlgorithm);
            PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
            DHParameterSpec dhParameterSpec = ((DHPublicKey) publicKey)
                    .getParams();

            keyPairGen = KeyPairGenerator
                    .getInstance(keyFactory.getAlgorithm());
            keyPairGen.initialize(dhParameterSpec);

        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvalidAlgorithmParameterException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        KeyPair keyPair = keyPairGen.generateKeyPair();

        // 公钥
        PublicKey publicKey = keyPair.getPublic();
        writeFile(publicKey.getEncoded(), publicClientkeyFile);

        // 私钥
        PrivateKey privateKey = keyPair.getPrivate();
        writeFile(privateKey.getEncoded(), privateClientkeyFile);
    }

    /**
     * 生成客户端机密密钥
     *
     * @return
     */
    private SecretKey getClientSecretKey() {
        byte[] privateClientKey = readFile(privateClientkeyFile);
        byte[] publicServerKey = readFile(publicServerkeyFile);

        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(publicServerKey);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(
                privateClientKey);

        PublicKey publicKey = null;
        KeyFactory keyFactory = null;
        Key privateKey = null;
        KeyAgreement keyAgree = null;

        try {
            keyFactory = KeyFactory.getInstance(keyAlgorithm);
            publicKey = keyFactory.generatePublic(x509KeySpec);
            // privateKey = keyFactory.generatePrivate(x509KeySpec);
            privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
            // 创建密钥协议
            keyAgree = KeyAgreement.getInstance(keyFactory.getAlgorithm());
            keyAgree.init(privateKey);
            keyAgree.doPhase(publicKey, true);
            return keyAgree.generateSecret(secretAlgorithm);
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 客户端数据解密
     *
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public byte[] decryptForClient() {
        SecretKey secretKey = getClientSecretKey();

        try {
            byte[] data = readFile(serverdataFile);
            Cipher cipher = Cipher.getInstance(secretKey.getAlgorithm());
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            return cipher.doFinal(data);
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (BadPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 客户端数据加密
     *
     * @param data
     */
    public void encryptForClient(byte[] data) {

        SecretKey secretKey = getClientSecretKey();

        try {
            Cipher cipher = Cipher.getInstance(secretKey.getAlgorithm());
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            writeFile(cipher.doFinal(data), clientdataFile);
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (BadPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static void main(String[] arg) {
        String data = "服务端你好,我是客户端";
        BothDHServerFile bothDHServerFile = new BothDHServerFile();
        BothDHClientFile bothDHClientFile = new BothDHClientFile();

        // 生成服务端密钥对
        bothDHServerFile.generateServerKeyFile();
        // 生成客户端密钥对
        bothDHClientFile.generateClientKeyFile();
        // 客户端加密
        bothDHClientFile.encryptForClient(data.getBytes());
        // 服务端解密
        byte[] data1 = bothDHServerFile.decryptForServer();
        System.out.println("Client原始数据:" + data);
        System.out.println("Servet解密数据:" + new String(data1));

    }
BothDHServerFile.java
    private String keyAlgorithm = "DH";
    private String secretAlgorithm = "DES";
    // 服务端数据文件
    private String serverdataFile = "fileServerData.dat";
    // 客户端数据文件
    private String clientdataFile = "fileClientData.dat";
    // 服务端私钥文件
    private String privateServerkeyFile = "keyServerPrivateData.dat";
    // 服务端公钥文件
    private String publicServerkeyFile = "keyServerPublicData.dat";
    // 客户端公钥文件
    private String publicClientkeyFile = "keyClientPublicData.dat";

    /**
     * 把数据写到指定的文件上
     *
     * @param data
     *            数据
     * @param fileName
     *            文件名称
     */
    public void writeFile(byte[] data, String fileName) {
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(fileName);
            fileOutputStream.write(data);
            fileOutputStream.close();
        } catch (FileNotFoundException e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 根据fileName读取数据文件
     *
     * @param fileName
     * @return
     */
    public byte[] readFile(String fileName) {

        // 读取
        try {
            File file = new File(fileName);
            FileInputStream fileInputStream = new FileInputStream(file);
            byte[] data = new byte[(int) file.length()];
            fileInputStream.read(data);
            fileInputStream.close();
            return data;
        } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;

    }

    /**
     * 生成服务端密钥对
     */
    public void generateServerKeyFile() {
        KeyPairGenerator keyPairGen = null;
        try {
            keyPairGen = KeyPairGenerator.getInstance(keyAlgorithm);
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        KeyPair keyPair = keyPairGen.generateKeyPair();

        // 公钥
        PublicKey publicKey = keyPair.getPublic();
        writeFile(publicKey.getEncoded(), publicServerkeyFile);

        // 私钥
        PrivateKey privateKey = keyPair.getPrivate();
        writeFile(privateKey.getEncoded(), privateServerkeyFile);
    }

    /**
     * 生成服务端机密密钥
     *
     * @return
     */
    private SecretKey getServerSecretKey() {
        byte[] privateServerKey = readFile(privateServerkeyFile);
        byte[] publicClientKey = readFile(publicClientkeyFile);

        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(publicClientKey);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(
                privateServerKey);

        Key publicKey = null;
        KeyFactory keyFactory = null;
        Key privateKey = null;
        KeyAgreement keyAgree = null;

        try {
            keyFactory = KeyFactory.getInstance(keyAlgorithm);
            publicKey = keyFactory.generatePublic(x509KeySpec);
            privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
            // 创建密钥协议
            keyAgree = KeyAgreement.getInstance(keyFactory.getAlgorithm());
            keyAgree.init(privateKey);
            keyAgree.doPhase(publicKey, true);
            return keyAgree.generateSecret(secretAlgorithm);
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 服务端数据加密
     *
     * @param data
     */
    public void encryptForServer(byte[] data) {

        SecretKey secretKey = getServerSecretKey();

        try {
            Cipher cipher = Cipher.getInstance(secretKey.getAlgorithm());
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            writeFile(cipher.doFinal(data), serverdataFile);
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (BadPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 服务端数据解密
     *
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public byte[] decryptForServer() {
        SecretKey secretKey = getServerSecretKey();

        try {
            byte[] data = readFile(clientdataFile);
            Cipher cipher = Cipher.getInstance(secretKey.getAlgorithm());
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            return cipher.doFinal(data);
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (BadPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] arg) {
        String data = "客户端你好,我是服务端";
        BothDHServerFile bothDHServerFile = new BothDHServerFile();
        BothDHClientFile bothDHClientFile = new BothDHClientFile();

        // 生成服务端密钥对
        bothDHServerFile.generateServerKeyFile();
        // 生成客户端密钥对
        bothDHClientFile.generateClientKeyFile();
        // 服务端加密
        bothDHServerFile.encryptForServer(data.getBytes());
        // 客户端解密
        byte[] data1 = bothDHClientFile.decryptForClient();
        System.out.println("Servet原始数据:" + data);
        System.out.println("Client解密数据:" + new String(data1));
    }

20.3  Java单项加密
实例546  使用MD5加密
    static String algorithm = "MD5";

    /**
     * MD5加密,返回byte[]类型
     *
     * @param data
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static byte[] encryptMD5(byte[] data)
            throws NoSuchAlgorithmException {
        MessageDigest digest = MessageDigest.getInstance(algorithm);
        digest.update(data);
        return digest.digest();
    }

    /**
     * 把MD5加密数据转换String类型
     *
     * @param data
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static String encryptMD5toString(byte[] data)
            throws NoSuchAlgorithmException {
        String str = "";
        String str16;
        System.out.println(data.length);
        for (int i = 0; i < data.length; i++) {
            str16 = Integer.toHexString(0xFF & data[i]);
            if (str16.length() == 1) {
                str = str + "0" + str16;
            } else {
                str = str + str16;
            }

        }
        return str;
    }

    public static void main(String[] avg) {
        String data = "明日科技";
        System.out.println("加密前:" + data);
        byte[] data1 = null;
        String str = null;
        try {
            data1 = SingleMD5.encryptMD5(data.getBytes());
            str = SingleMD5.encryptMD5toString(data1);
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("加密后byte[]类型:" + new String(data1));
        System.out.println("加密后String类型:" + str);

    }

实例547  使用Hmac加密
BothBase64.java
    public static String encryptBASE64(byte[] data) {
        return (new BASE64Encoder()).encodeBuffer(data);
    }

    /**
     * 解密
     *
     * @param data
     * @return
     * @throws IOException
     */
    public static byte[] decryptBASE64(String data) throws IOException {
        return (new BASE64Decoder()).decodeBuffer(data);
    }

    public static void main(String[] avg) {
        String data = "明日科技";
        System.out.println("加密前:" + data);
        String data1 = BothBase64.encryptBASE64(data.getBytes());
        System.out.println("加密后:" + data1);
        byte[] data2 = null;
        try {
            data2 = BothBase64.decryptBASE64(data1);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("解密后:" + new String(data2));
    }
SingleHmacClientFile.java
    static String algorithm = "HmacMD5";

    static String keyFile = "keyData.dat";
    static String dataFile = "fileData.dat";

    /**
     * HMAC加密
     *
     * @param data
     * @param key
     * @return
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeyException
     */
    public byte[] encryptHMAC(byte[] data) throws NoSuchAlgorithmException,
            InvalidKeyException {
        byte key[] = readFile(keyFile);
        SecretKey secretKey = new SecretKeySpec(key, algorithm);
        Mac mac = Mac.getInstance(secretKey.getAlgorithm());
        mac.init(secretKey);
        return mac.doFinal();

    }
    
    /**
     * 根据fileName读取数据文件
     *
     * @param fileName
     * @return
     */
    public byte[] readFile(String fileName) {

        // 读取
        try {
            File file = new File(fileName);
            FileInputStream fileInputStream = new FileInputStream(file);
            byte[] data = new byte[(int) file.length()];
            fileInputStream.read(data);
            fileInputStream.close();
            return data;
        } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
SingleHmacServerFile.java
    static String algorithm = "HmacMD5";

    static String keyFile = "keyData.dat";

    /**
     * 生成密钥
     *
     * @return
     * @throws NoSuchAlgorithmException
     */
    public void initMacKey() throws NoSuchAlgorithmException {
        KeyGenerator generator = KeyGenerator.getInstance(algorithm);
        SecretKey key = generator.generateKey();

        writeFile(key.getEncoded(), keyFile);
    }

    /**
     * HMAC加密
     *
     * @param data
     * @param key
     * @return
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeyException
     */
    public byte[] encryptHMAC(byte[] data) throws NoSuchAlgorithmException,
            InvalidKeyException {
        byte key[] = readFile(keyFile);
        SecretKey secretKey = new SecretKeySpec(key, algorithm);
        Mac mac = Mac.getInstance(secretKey.getAlgorithm());
        mac.init(secretKey);
        return mac.doFinal();

    }

    /**
     * 把数据写到指定的文件上
     *
     * @param data
     *            数据
     * @param fileName
     *            文件名称
     */
    public void writeFile(byte[] data, String fileName) {
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(fileName);
            fileOutputStream.write(data);
            fileOutputStream.close();
        } catch (FileNotFoundException e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 根据fileName读取数据文件
     *
     * @param fileName
     * @return
     */
    public byte[] readFile(String fileName) {

        // 读取
        try {
            File file = new File(fileName);
            FileInputStream fileInputStream = new FileInputStream(file);
            byte[] data = new byte[(int) file.length()];
            fileInputStream.read(data);
            fileInputStream.close();
            return data;
        } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;

    }

    public static void main(String[] avg) throws NoSuchAlgorithmException, InvalidKeyException {
        SingleHmacServerFile singleHmacServerFile = new SingleHmacServerFile();
        SingleHmacClientFile singleHmacClientFile = new SingleHmacClientFile();
        String data = "明日科技";
        System.out.println("加密前:" + data);
        String strData = null;
        String strDataClient = null;

        singleHmacServerFile.initMacKey();
        strData = BothBase64.encryptBASE64(singleHmacServerFile.encryptHMAC(data.getBytes()));
        strDataClient = BothBase64.encryptBASE64(singleHmacClientFile.encryptHMAC(data.getBytes()));
        
        System.out.println("服务端加密后:" + strData);
        System.out.println("客户端加密后:" + strDataClient);
        if (strData.equals(strDataClient)) {
            System.out.println("验证通过");
        } else {
            System.out.println("验证不通过");
        }
    }

实例548  使用DSA加密
SingleDSAClientFile.java
    static String algorithm = "DSA";

    static String signdataFile = "fileSignData.dat";
    static String publickeyFile = "keyPublicData.dat";

    /**
     * 用数字签名进行验证
     *
     * @param data
     * @return
     */
    public boolean verifySign(byte[] data) {

        byte[] key = readFile(publickeyFile);
        byte[] sign = readFile(signdataFile);

        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(key);
        KeyFactory keyFactory = null;
        PublicKey publicKey = null;

        try {
            // 获取公钥匙
            keyFactory = KeyFactory.getInstance(algorithm);
            publicKey = keyFactory.generatePublic(keySpec);
        } catch (InvalidKeySpecException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        try {
            // 验证数字签名
            Signature signature = Signature.getInstance(keyFactory
                    .getAlgorithm());
            signature.initVerify(publicKey);
            signature.update(data);
            return signature.verify(sign);
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SignatureException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 根据fileName读取数据文件
     *
     * @param fileName
     * @return
     */
    public byte[] readFile(String fileName) {

        // 读取
        try {
            File file = new File(fileName);
            FileInputStream fileInputStream = new FileInputStream(file);
            byte[] data = new byte[(int) file.length()];
            fileInputStream.read(data);
            fileInputStream.close();
            return data;
        } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;

    }
SingleDSAServerFile.java
    static String algorithm = "DSA";

    static String signdataFile = "fileSignData.dat";
    static String privatekeyFile = "keyPrivateData.dat";
    static String publickeyFile = "keyPublicData.dat";

    /**
     * 生成密钥对
     *
     * @return
     * @throws NoSuchAlgorithmException
     */
    public void generatorKey() {
        KeyPairGenerator generator = null;
        try {
            generator = KeyPairGenerator.getInstance(algorithm);
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        KeyPair keyPair = generator.generateKeyPair();
        PublicKey publicKey = keyPair.getPublic();
        PrivateKey privateKey = keyPair.getPrivate();
        writeFile(publicKey.getEncoded(), publickeyFile);
        writeFile(privateKey.getEncoded(), privatekeyFile);
    }

    /**
     * 生成签名
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeySpecException
     * @throws InvalidKeyException
     * @throws SignatureException
     */
    public void generatorSign(byte[] data) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, SignatureException {

        byte[] privateKey = readFile(privatekeyFile);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(privateKey);

        // algorithm 指定的加密算法
        KeyFactory keyFactory = null;
        PrivateKey priKey = null;
        keyFactory = KeyFactory.getInstance(algorithm);
        priKey = keyFactory.generatePrivate(pkcs8KeySpec);
        Signature signature = Signature.getInstance(keyFactory.getAlgorithm());
        signature.initSign(priKey);
        signature.update(data);
        writeFile(signature.sign(), signdataFile);
    }

    /**
     * 把数据写到指定的文件上
     *
     * @param data
     *            数据
     * @param fileName
     *            文件名称
     */
    public void writeFile(byte[] data, String fileName) {
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(fileName);
            fileOutputStream.write(data);
            fileOutputStream.close();
        } catch (FileNotFoundException e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 根据fileName读取数据文件
     *
     * @param fileName
     * @return
     */
    public byte[] readFile(String fileName) {

        // 读取
        try {
            File file = new File(fileName);
            FileInputStream fileInputStream = new FileInputStream(file);
            byte[] data = new byte[(int) file.length()];
            fileInputStream.read(data);
            fileInputStream.close();
            return data;
        } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;

    }

    public static void main(String[] avg) throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, SignatureException {

        SingleDSAServerFile singleDSAServerFile = new SingleDSAServerFile();
        SingleDSAClientFile singleDSAClientFile = new SingleDSAClientFile();
        String data = "明日科技";
        System.out.println("传输数据:" + data);
        boolean flag = false;

        singleDSAServerFile.generatorKey();
        singleDSAServerFile.generatorSign(data.getBytes());

        flag = singleDSAClientFile.verifySign(data.getBytes());

        if (flag) {
            System.out.println("验证通过,数据传输过程没有经过修改");
        } else {
            System.out.println("验证不过通,数据传输过程经过修改");
        }
    }

 

这篇关于Java开发实例大全提高篇——Java安全的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1146599

相关文章

java中pdf模版填充表单踩坑实战记录(itextPdf、openPdf、pdfbox)

《java中pdf模版填充表单踩坑实战记录(itextPdf、openPdf、pdfbox)》:本文主要介绍java中pdf模版填充表单踩坑的相关资料,OpenPDF、iText、PDFBox是三... 目录准备Pdf模版方法1:itextpdf7填充表单(1)加入依赖(2)代码(3)遇到的问题方法2:pd

Java Stream流之GroupBy的用法及应用场景

《JavaStream流之GroupBy的用法及应用场景》本教程将详细介绍如何在Java中使用Stream流的groupby方法,包括基本用法和一些常见的实际应用场景,感兴趣的朋友一起看看吧... 目录Java Stream流之GroupBy的用法1. 前言2. 基础概念什么是 GroupBy?Stream

SpringBoot监控API请求耗时的6中解决解决方案

《SpringBoot监控API请求耗时的6中解决解决方案》本文介绍SpringBoot中记录API请求耗时的6种方案,包括手动埋点、AOP切面、拦截器、Filter、事件监听、Micrometer+... 目录1. 简介2.实战案例2.1 手动记录2.2 自定义AOP记录2.3 拦截器技术2.4 使用Fi

最新Spring Security的基于内存用户认证方式

《最新SpringSecurity的基于内存用户认证方式》本文讲解SpringSecurity内存认证配置,适用于开发、测试等场景,通过代码创建用户及权限管理,支持密码加密,虽简单但不持久化,生产环... 目录1. 前言2. 因何选择内存认证?3. 基础配置实战❶ 创建Spring Security配置文件

Spring Security 单点登录与自动登录机制的实现原理

《SpringSecurity单点登录与自动登录机制的实现原理》本文探讨SpringSecurity实现单点登录(SSO)与自动登录机制,涵盖JWT跨系统认证、RememberMe持久化Token... 目录一、核心概念解析1.1 单点登录(SSO)1.2 自动登录(Remember Me)二、代码分析三、

PyQt5 GUI 开发的基础知识

《PyQt5GUI开发的基础知识》Qt是一个跨平台的C++图形用户界面开发框架,支持GUI和非GUI程序开发,本文介绍了使用PyQt5进行界面开发的基础知识,包括创建简单窗口、常用控件、窗口属性设... 目录简介第一个PyQt程序最常用的三个功能模块控件QPushButton(按钮)控件QLable(纯文本

springboot自定义注解RateLimiter限流注解技术文档详解

《springboot自定义注解RateLimiter限流注解技术文档详解》文章介绍了限流技术的概念、作用及实现方式,通过SpringAOP拦截方法、缓存存储计数器,结合注解、枚举、异常类等核心组件,... 目录什么是限流系统架构核心组件详解1. 限流注解 (@RateLimiter)2. 限流类型枚举 (

Java Thread中join方法使用举例详解

《JavaThread中join方法使用举例详解》JavaThread中join()方法主要是让调用改方法的thread完成run方法里面的东西后,在执行join()方法后面的代码,这篇文章主要介绍... 目录前言1.join()方法的定义和作用2.join()方法的三个重载版本3.join()方法的工作原

Spring AI使用tool Calling和MCP的示例详解

《SpringAI使用toolCalling和MCP的示例详解》SpringAI1.0.0.M6引入ToolCalling与MCP协议,提升AI与工具交互的扩展性与标准化,支持信息检索、行动执行等... 目录深入探索 Spring AI聊天接口示例Function CallingMCPSTDIOSSE结束语

Java获取当前时间String类型和Date类型方式

《Java获取当前时间String类型和Date类型方式》:本文主要介绍Java获取当前时间String类型和Date类型方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,... 目录Java获取当前时间String和Date类型String类型和Date类型输出结果总结Java获取