国家专用加密数据传输之rsa,3des加密方法-rasor3desc

前言

公司项目需要对接国家市抽(器检市抽)表示必须使用3des加密来data(响应重要数据)以及使用rsa进行验证签名。

3des是什么?

DES全称为Data Encryption Standard,对称加密,即数据加密标准,是一种使用密钥加密的块算法,1977年被美国联邦政府的国家标准局确定为联邦资料处理标准(FIPS),并授权在非密级政府通信中使用,随后该算法在国际上广泛流传开来。

3DES就是三重DES,它相当于是对每个数据块应用三次DES加密算法,
3DES加密过程为:C=Ek3(Dk2(Ek1(M)))
3DES解密过程为:M=Dk1(EK2(Dk3(C)))

3des代码示例演示

public class DesUtil {
    private static final Logger logger = Logger.getLogger(DesUtil.class);
    private static final String ALGORITHM = "DESede";   

 /**
     * 获取16进制随机数
     * 密钥key
     *
     * @param len
     * @return
     */
    public static String randomHexString(int len) {
        try {
            StringBuilder result = new StringBuilder();
            for (int i = 0; i < len; i++) {
                result.append(Integer.toHexString(new Random().nextInt(16)));
            }
            return result.toString().toUpperCase();

        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();

        }
        return null;

    }

  @Test
    public void one() {
        // 获取私钥
//        String s1 = randomHexString(48);
        // 48 位 key
        String privateKey = "E825FD03506807064F4526D9033BB643DC8D118E8D7B761C";
        try {
            String s = encryptMode("yangbuyi", privateKey);
            System.out.println("加密:" + s);
            String s1 = decryptMode(s, privateKey);
            System.out.println("解密:" + s1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}


   /***************************************************市抽提供************************************************/

    /**
     * * @Description: 3DES加密,用户对请求体加密
     * * @param data 待加密内容
     * * @param desKey 密钥
     * <p>
     * * @return String
     */
    public static String encryptMode(String data, String desKey) throws Exception {
        Date startDate = new Date();
        logger.info("encryptMode begin : " + startDate);
        SecretKey deskey = new SecretKeySpec(Hex.decodeHex(desKey.toCharArray()), ALGORITHM);
        Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, deskey);
        byte[] bytes = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
        String encryptTxt = Base64.encodeBase64String(bytes);
        logger.info("encryptMode run end(s) : " + startDate);
        return encryptTxt;
    }

    /****
     *  3DES解密
     *  @param encryptTxt 待解密内容
     *  @return String
     *  @date 2019/8/1
     *  */
    public static String decryptMode(String encryptTxt, String desKey) throws Exception {
        Date startDate = new Date();
        logger.info("decryptMode begin : " + startDate);
        SecretKey deskey = new SecretKeySpec(Hex.decodeHex(desKey.toCharArray()), ALGORITHM);
        Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, deskey);
        // 进行解密
        byte[] bytes = cipher.doFinal(Base64.decodeBase64(encryptTxt));
        String decryptTxt = new String(bytes, StandardCharsets.UTF_8);
        logger.info("decryptMode run end(s) : " + startDate);
        return decryptTxt;
    }

image

ras加密是什么?

RSA又叫非对称加密算法,这类加密算法有一对秘钥,其中一个用来加密一个用来解密。这一对秘钥中你可以选择一个作为私钥(自己保存),另一个作为公钥(对外公开)。用私钥加密的内容只能用对应的公钥解密,反之用公钥加密的内容只能用对应的私钥解密。还有一种对称加密算法,其加密秘钥和解密秘钥为同一个秘钥,比如DES。

代码示例


public class RsaSignUtil {
    private static final Logger logger = Logger.getLogger(RsaSignUtil.class);
    /**
     * RSA最大加密明文大小
     */
    private static final int MAX_ENCRYPT_BLOCK = 117;

    /**
     * RSA最大解密密文大小
     */
    private static final int MAX_DECRYPT_BLOCK = 128;

    /**
     * 获取密钥对
     *
     * @return 密钥对
     */
    public static KeyPair getKeyPair() throws Exception {
        KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
        generator.initialize(1024);
        return generator.generateKeyPair();
    }


   /***
     * 获取私钥
     * @param privateKey 私钥字符串
     * @return PrivateKey
     **/
    public static PrivateKey getPrivateKey(String privateKey) throws Exception {
        Date startDate = new Date();
        logger.info("getPrivateKey begin : " + startDate);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        byte[] decodedKey = Base64.decodeBase64(privateKey.getBytes());
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodedKey);
        logger.info("getPrivateKey run end(s) : " + startDate);
        return keyFactory.generatePrivate(keySpec);
    }

    /***
     * 获取公钥
     * @param publicKey 公钥字符串
     * @return PublicKey
     * */
    public static PublicKey getPublicKey(String publicKey) throws Exception {
        Date startDate = new Date();
        logger.info("getPublicKey begin : " + startDate);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        byte[] decodedKey = Base64.decodeBase64(publicKey.getBytes());
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(decodedKey);
        logger.info("getPublicKey run end(s) : " + (startDate));
        return keyFactory.generatePublic(keySpec);
    }

    /***
     * 生成签名
     * @param data 待签名数据
     * @param privateKey 私钥
     * @return 签名
     * */
    public static String sign(String data, PrivateKey privateKey) throws Exception {
        Date startDate = new Date();
        logger.info("sign begin : " + startDate);
        byte[] keyBytes = privateKey.getEncoded();
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey key = keyFactory.generatePrivate(keySpec);
        Signature signature = Signature.getInstance("MD5withRSA");
        signature.initSign(key);
        signature.update(data.getBytes());
        logger.info("sign run end(s) : " + (startDate));
        return new String(Base64.encodeBase64(signature.sign()));
    }

    /***
     * 验签
     * @param publicMap 原始待签名组装字符串
     * @param publicKey 公钥
     * @return 是否验签通过
     * */
    public static boolean verify(Map publicMap, PublicKey publicKey) throws Exception {
        String sign = String.valueOf(publicMap.get("sign"));
        String appid = String.valueOf(publicMap.get("appId"));
        String data = String.valueOf(publicMap.get("data"));
        String timestamp = String.valueOf(publicMap.get("timestamp"));
        String waitData = appid + data + timestamp;
        Date startDate = new Date();
        logger.info("verify begin : " + startDate);
        byte[] keyBytes = publicKey.getEncoded();
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey key = keyFactory.generatePublic(keySpec);
        Signature signature = Signature.getInstance("MD5withRSA");
        signature.initVerify(key);
        signature.update(waitData.getBytes());
        logger.info("verify run end(s) : " + (startDate));
        return signature.verify(Base64.decodeBase64(sign.getBytes()));
    }

}

模拟数据传输的格式

{
"appId": "test",
"data": "真正要传输的数据经过3DES加密后密文",
"timestamp": 123213123,
"sign": "AppId&3DES加密后密文&timestamp => 生成签名值"
}

传输结果反馈的格式:以下内容整体使用3DES加密传回的3DES密文!
{
"code": 20000,
"msg": "数据处理成功",
"data": "如有必要数据则加密回传"
}

测试ras加密

  // 3desc 私钥 可自行生成
    String descPrivate = "E825FD03506807064F4526D9033BB643DC8D118E8D7B761C";

@Test
    public void test() throws Exception {
        // 生成密钥对
        KeyPair keyPair = getKeyPair();
        String privateKey = new String(Base64.encodeBase64(keyPair.getPrivate().getEncoded()));
        String publicKey = new String(Base64.encodeBase64(keyPair.getPublic().getEncoded()));
        System.out.println("私钥:" + privateKey);
        System.out.println("公钥:" + publicKey);

        Map<String, Object> map = new HashMap<>();
        // 组装数据传输
        String appid = "test";
        Timestamp timestamp = DateUtil.date().toTimestamp();
        map.put("appId", appid);
        // 加密data数据(3des)
        String s = DesUtil.encryptMode("你要对称加密的敏感数据", descPrivate);
        map.put("data", s);
        map.put("timestamp", timestamp.getTime());
        // 组装签名 私钥签名
        // 获取签名
        String waitingSign = appid + s + timestamp.getTime();
        try {
            // 生成签名
            map.put("sign", sign(waitingSign, getPrivateKey(privateKey)));
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("最终加密:" + JsonUtils.toJsonStr(map));
        // 解密
        String publicJson = JsonUtils.toJsonStr(map);
        Map publicMap = JsonUtils.toObject(publicJson, map.getClass());
        // 获取data数据
        String publicData = DesUtil.decryptMode(publicMap.get("data").toString(), descPrivate);
        System.out.println("最终解密:" + publicData);
        // RSA验签
        boolean result = verify(publicMap, getPublicKey(publicKey));
        System.out.print("验签结果:" + result);
    }

image.png

posted @ 2023-05-19 11:55  杨不易呀  阅读(78)  评论(0编辑  收藏  举报