Java教程

对称加密和非对称工具类

本文主要是介绍对称加密和非对称工具类,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

加密方法有对称加密和非对称加密两种。
对称加密是key+明文==加密后的数据
然后服务端得到加密后的数据和key解密得到明文。
这里key是一致的。
非对称加密是key是不一致的。安全,但效率低。

这里需要base64工具类,因为生成的乱码会在传输的过程中出问题。比如说我在这加密了一套算法,服务端那边拿到解密却不是这一套算法,这不是乱套了么,,所以最好规定一套公共的,加密解密都用这种算法才不会出问题。

Base64Util.java

package com.coder520.mamabike.security;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class Base64Util {
    private static final char[] legalChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
            .toCharArray();



    public static String encode(byte[] data) {
        byte start = 0;
        int len = data.length;
        StringBuffer buf = new StringBuffer(data.length * 3 / 2);
        int end = len - 3;
        int i = start;
        int n = 0;

        int d;
        while (i <= end) {
            d = (data[i] & 255) << 16 | (data[i + 1] & 255) << 8 | data[i + 2] & 255;
            buf.append(legalChars[d >> 18 & 63]);
            buf.append(legalChars[d >> 12 & 63]);
            buf.append(legalChars[d >> 6 & 63]);
            buf.append(legalChars[d & 63]);
            i += 3;
            if (n++ >= 14) {
                n = 0;
                buf.append(" ");
            }
        }

        if (i == start + len - 2) {
            d = (data[i] & 255) << 16 | (data[i + 1] & 255) << 8;
            buf.append(legalChars[d >> 18 & 63]);
            buf.append(legalChars[d >> 12 & 63]);
            buf.append(legalChars[d >> 6 & 63]);
            buf.append("=");
        } else if (i == start + len - 1) {
            d = (data[i] & 255) << 16;
            buf.append(legalChars[d >> 18 & 63]);
            buf.append(legalChars[d >> 12 & 63]);
            buf.append("==");
        }

        return buf.toString();
    }

    private static int decode(char c) {
        if (c >= 65 && c <= 90) {
            return c - 65;
        } else if (c >= 97 && c <= 122) {
            return c - 97 + 26;
        } else if (c >= 48 && c <= 57) {
            return c - 48 + 26 + 26;
        } else {
            switch (c) {
            case '+':
                return 62;
            case '/':
                return 63;
            case '=':
                return 0;
            default:
                throw new RuntimeException("unexpected code: " + c);
            }
        }
    }

    public static byte[] decode(String s) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        try {
            decode(s, bos);
        } catch (IOException var5) {
            throw new RuntimeException();
        }

        byte[] decodedBytes = bos.toByteArray();

        try {
            bos.close();
            bos = null;
        } catch (IOException var4) {
            System.err.println("Error while decoding BASE64: " + var4.toString());
        }

        return decodedBytes;
    }

    private static void decode(String s, OutputStream os) throws IOException {
        int i = 0;
        int len = s.length();

        while (true) {
            while (i < len && s.charAt(i) <= 32) {
                ++i;
            }

            if (i == len) {
                break;
            }

            int tri = (decode(s.charAt(i)) << 18) + (decode(s.charAt(i + 1)) << 12) + (decode(s.charAt(i + 2)) << 6)
                    + decode(s.charAt(i + 3));
            os.write(tri >> 16 & 255);
            if (s.charAt(i + 2) == 61) {
                break;
            }

            os.write(tri >> 8 & 255);
            if (s.charAt(i + 3) == 61) {
                break;
            }

            os.write(tri & 255);
            i += 4;
        }

    }

}

AESUtil.java

package com.coder520.mamabike.security;

import org.springframework.stereotype.Component;

import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * Created by JackWangon[www.coder520.com] 2017/7/31.
 */

public class AESUtil {


    public static final String KEY_ALGORITHM = "AES";
    public static final String KEY_ALGORITHM_MODE = "AES/CBC/PKCS5Padding";


    /**
     * AES对称加密
     * @param data
     * @param key key需要16位
     * @return
     */
    public static String encrypt(String data , String key) {
        try {
            SecretKeySpec spec = new SecretKeySpec(key.getBytes("UTF-8"),KEY_ALGORITHM);
            Cipher cipher = Cipher.getInstance(KEY_ALGORITHM_MODE);
            cipher.init(Cipher.ENCRYPT_MODE , spec,new IvParameterSpec(new byte[cipher.getBlockSize()]));
            byte[] bs = cipher.doFinal(data.getBytes("UTF-8"));
            return Base64Util.encode(bs);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  null;
    }


    /**
     * AES对称解密 key需要16位
     * @param data
     * @param key
     * @return
     */
    public static String decrypt(String data, String key) {
        try {
            SecretKeySpec spec = new SecretKeySpec(key.getBytes("UTF-8"), KEY_ALGORITHM);
            Cipher cipher = Cipher.getInstance(KEY_ALGORITHM_MODE);
            cipher.init(Cipher.DECRYPT_MODE , spec , new IvParameterSpec(new byte[cipher.getBlockSize()]));
            byte[] originBytes = Base64Util.decode(data);
            byte[] result = cipher.doFinal(originBytes);
            return new String(result,"UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  null;
    }


    public static void main(String[] args) throws Exception {

        String s="123456789qazwsx";
        String encrypt = AESUtil.encrypt(s, "123456789qazwsxc");
        System.out.println(encrypt);
        String decrypt = AESUtil.decrypt(encrypt, "123456789qazwsxc");
        System.out.println(decrypt);

        /*String okey = "123456789abcdefg";
        //移动端随机key  AES加密数据
       String enr= encrypt("{'mobile':'18980840843','code':'8060','platform':'android','channelId':12454348}",okey);
       System.out.println(enr);
       //移动端RSA加密AES的key 和加密的数据一起传到服务器
       byte[] keyrsa = RSAUtil.encryptByPublicKey(okey.getBytes("UTF-8"),"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCuVRY8B3+Af5euC9WbgNkJKAiBzqOvrYi9mSST78jd4clpn7vkYHDfHzJiqFz9wjNRLzg9MUREF53bw9yhSljZ7F8JPMryfe8RR2Ed6CJq5nCy/2hvTTw4L6ypDemwe9f9yjIg52oPRPwU8lm8Uj3wKhjedDmZrkO1TAmt3sbQtwIDAQAB");
       System.out.println(Base64Util.encode(keyrsa));
       String base = Base64Util.encode(keyrsa);*/

//       //服务端RSA解密AES的key
//       byte[] keybyte= RSAUtil.decryptByPrivateKey(Base64Util.decode(base));
//       String keyR=new String(keybyte,"UTF-8");
//        System.out.println(keyR);
    }
}

非对称加密大概思路

1。首先通过javax的包,不用引入其他包,里面的类得到公钥和私钥。

 public static void main(String[] args) throws Exception {
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
        keyPairGen.initialize(1024);
        KeyPair keyPair = keyPairGen.generateKeyPair();
        PrivateKey privateKey = keyPair.getPrivate();
        PublicKey publicKey = keyPair.getPublic();
        System.out.println(Base64Util.encode(privateKey.getEncoded()));  //私钥
        System.out.println(Base64Util.encode(publicKey.getEncoded()));   //公钥
    }

2。然后通过公钥加密返回一个byte[]数组。 注意:这里第一个参数传的数组需要加密的key.getBytes(“UTF-8”)得到,第二个参数就是字符串的公钥

   /**
     *
     * @param data
     * @param key
     * @return      公钥加密
     * @throws Exception
     */
    public static byte[] encryptByPublicKey(byte[] data, String key) throws Exception {
        byte[] keyBytes = Base64Util.decode(key);
        X509EncodedKeySpec pkcs8KeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key publicKey = keyFactory.generatePublic(pkcs8KeySpec);

//        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        return cipher.doFinal(data);
    }

3。然后通过返回加密返回的byte[]数组和私钥解密,返回的还是byte[]数组,new String(bytes1,”UTF-8”)这种解密就可以得到字符串key。

 /**
     * 私钥解密
     *
     * @param data
     * @return
     * @throws Exception
     */
    public static byte[] decryptByPrivateKey(byte[] data) throws Exception {
        convert();  //先读取私钥
        byte[] keyBytes = Base64Util.decode(PRIVATE_KEY);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        return cipher.doFinal(data);
    }

main函数测试

 public static void main(String[] args) throws Exception {

        String data="孙悟空来了----";
        String key="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCoxN+GpRBuQT1+J72rVtyX GADOn1peU7kaLQ+CLxisx3+n9sdUWnF85Av6miE829NQ4G6R1J7wt2JnuMir 89/BHBie4L19H8qMnVpyWEVBtGWiy8A/Zw9IdL21v1+e1v1NEUIVvws/nyrf +shjI/jIVajz6h1Ql/z/aDpl1KMYLwIDAQAB";
        //公钥加密
        byte[] bytes = encryptByPublicKey(data.getBytes("UTF-8"), key);
         //私钥解密
        byte[] bytes1 = decryptByPrivateKey(bytes);
        System.out.println(new String(bytes1,"UTF-8"));
    }

总结:采用对称和非对称加密相结合的方法来解决问题。

第一:采用对称方法拿到加密过后的数据。但是key在http协议中传输不安全,然后采用非对称加密的方法来加密key。把加密后的数据和加密后的key传到服务端。注意:加密后的key使用RSAUtil.encryptByPublicKey()方法返回的是数组,需要传字符串,所以需要用Base64Util.encode(bytes)来得到字符串。。。不然乱码!!!!!!!!!!!
第二:服务端拿到加密后的key之后,将key解密出来。然后再根据key和加密的数据来解密加密过的数据。

 String okey="123456789abcdefg";
        String enr= encrypt("{'mobile':'15515664xxx','code':'8888','platform':'android'}",okey);
        System.out.println(enr);//加密后的数据

        byte[] bytes = RSAUtil.encryptByPublicKey(okey.getBytes("UTF-8"), "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCoxN+GpRBuQT1+J72rVtyX GADOn1peU7kaLQ+CLxisx3+n9sdUWnF85Av6miE829NQ4G6R1J7wt2JnuMir 89/BHBie4L19H8qMnVpyWEVBtGWiy8A/Zw9IdL21v1+e1v1NEUIVvws/nyrf +shjI/jIVajz6h1Ql/z/aDpl1KMYLwIDAQAB");
        System.out.println(Base64Util.encode(bytes));//公钥加密的key

这个就是客户端传送的加密后的数据,和公钥加密的key。
服务器端先解密key,然后再解密加密的数据。

//RSA解密AES的key
byte[] aesKey = RSAUtil.decryptByPrivateKey(Base64Util.decode(key));
 //AES的key解密AES加密数据
 decryptData = AESUtil.decrypt(data, new String(aesKey, "UTF-8"));

理下思路:

首先我需要传送一个加密的数据和一个公钥加密的key。但是公钥加密的key返回的是数组,所以我需要用Base64来转成字符串。
然后后台接收到字符串后,又用Base64转换成数组然后解密key。得到的还是数组。这时候就不用Bash64了
得到key之后,再解密数据

这篇关于对称加密和非对称工具类的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!