数据安全策略

209 阅读4分钟

数据安全

前言:基于本人从事对接国外支付的工作,需要在数据安全方面研究各种哈希算法、加密算法、验签算法等,也借着这个机会,在掘金开始发布技术相关文章,后续会在这里更新所有的源码(Java),首先我要分享的就是关于数据安全的相关源码,包括RSA、AES、hash算法(MD5、SHA1、SHA256、SHA512...)
数据安全对于敏感型业务非常重要,比如支付业务,对数据安全性要求极高,那么在应用层面,如何保证数据是安全的?也就是说即使攻击者获取到了请求接口和传输报文,也攻击不了我们的应用,因此就需要对数据进行加密.
说明:https协议在http协议的基础上加入了ssl协议,保证了在网络传输中数据的安全,但是不能保证应用层面的数据安全。
常见的用于数据安全的算法: 哈希算法和加密算法:

基于java的哈希算法实现

package algorithm.hash;

import algorithm.hash.vo.HMACEncryptType;
import algorithm.hash.vo.SHAEncryptType;
import org.apache.commons.codec.binary.Hex;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author lyq
 * @Fuction hash算法,不可逆,加密后的数据长度固定
 * @Method hash加密,基于Mac的哈希加密
 */

public class HashAlgorithmUtils {

    /**
     * hash加密算法
     * @param string 目标字符串
     * @param type   加密类型 {@link HashEncryptType}
     */
    public static String hashEncryption(String string, HashEncryptType type) {
        if (string==null || "".equals(string.trim())) return "";
        if (type==null) type = SHAEncryptType.SHA512;
        try {
            MessageDigest md = MessageDigest.getInstance(type.value);
            byte[] bytes = md.digest((string).getBytes());
            byte[] hex = new Hex().encode(bytes);
            return new String(hex);
        } catch (NoSuchAlgorithmException e) {

        }
        return "";
    }


    /**
     * 基于Mac的加密算法
     * @param data
     * @param key
     * @param type {@link HMACEncryptType}
     * @return
     */
    public static String hmacHashEncryption(String data, String key, HMACEncryptType type) {
        String result = "";
        byte[] bytesKey = key.getBytes();
        final SecretKeySpec secretKey = new SecretKeySpec(bytesKey, type.value);
        try {
            Mac mac = Mac.getInstance(type.value);
            mac.init(secretKey);
            final byte[] macData = mac.doFinal(data.getBytes());
            byte[] hex = new Hex().encode(macData);
            result = new String(hex);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

}

package algorithm.hash.vo;

import lombok.AllArgsConstructor;

@AllArgsConstructor
public enum HMACEncryptType {

    HMACMD5("HmacMD5"),
    HMACSHA1("HmacSHA1"),
    HMACSHA256("HmacSHA256"),
    HMACSHA512("HmacSHA512");

    public String value;
}

package algorithm.hash.vo;

import lombok.AllArgsConstructor;

@AllArgsConstructor
public enum HashEncryptType {
    MD5("md5"),
    SHA1("sha-1"),
    SHA224("sha-224"),
    SHA256("sha-256"),
    SHA384("sha-384"),
    SHA512("sha-512"),
    ;

    public String value;

}

package algorithm.hash;


import algorithm.hash.vo.HMACEncryptType;
import algorithm.hash.vo.SHAEncryptType;

public class TestHash {

    public static void main(String[] args) {
        //test hmac
        String key = "sk_live_2270105ca7e207b3b3e5a56dd04c493549cef964";
        String data = "{\"event\":\"charge.success\",\"data\":{\"id\":1183164216,\"domain\":\"live\",\"status\":\"success\",\"reference\":\"210621070140pch92309406\",\"amount\":50000,\"message\":null,\"gateway_response\":\"Approved by Financial Institution\",\"paid_at\":\"2021-06-21T07:01:47.000Z\",\"created_at\":\"2021-06-21T07:01:41.000Z\",\"channel\":\"card\",\"currency\":\"NGN\",\"ip_address\":\"52.49.173.169\",\"metadata\":\"\",\"log\":null,\"fees\":400,\"fees_split\":null,\"authorization\":{\"authorization_code\":\"AUTH_jify7ej4xz\",\"bin\":\"506105\",\"last4\":\"9270\",\"exp_month\":\"06\",\"exp_year\":\"2022\",\"channel\":\"card\",\"card_type\":\"verve DEBIT\",\"bank\":\"First Bank of Nigeria\",\"country_code\":\"NG\",\"brand\":\"verve\",\"reusable\":true,\"signature\":\"SIG_KIrnvMgIz4nevoGpB22A\",\"account_name\":\"OWANIYI LAWRENCE GBENGA\"},\"customer\":{\"id\":29527446,\"first_name\":null,\"last_name\":null,\"email\":\"200908163344puid22741529@msport.com\",\"customer_code\":\"CUS_ka3zv3h6j99d2x7\",\"phone\":null,\"metadata\":null,\"risk_action\":\"default\",\"international_format_phone\":null},\"plan\":{},\"subaccount\":{},\"split\":{},\"order_id\":null,\"paidAt\":\"2021-06-21T07:01:47.000Z\",\"requested_amount\":50000,\"pos_transaction_data\":null,\"source\":{\"type\":\"api\",\"source\":\"merchant_api\",\"identifier\":null}},\"order\":null,\"business_name\":\"MSPORT\"}";
        String result = HashAlgorithmUtils.hmacHashEncryption(data, key, HMACEncryptType.HMACSHA512);
        System.out.println(result);

        //test hash
        String str = "abc123";
        String md5 = HashAlgorithmUtils.hashEncryption(str, SHAEncryptType.MD5);
        String sha1 = HashAlgorithmUtils.hashEncryption(str, SHAEncryptType.SHA1);
        String sha256 = HashAlgorithmUtils.hashEncryption(str, SHAEncryptType.SHA256);
        String sha512 = HashAlgorithmUtils.hashEncryption(str, SHAEncryptType.SHA512);
        System.out.println(md5);
        System.out.println(sha1);
        System.out.println(sha256);
        System.out.println(sha512);
    }
}

package algorithm.hash;


import algorithm.hash.vo.HMACEncryptType;
import algorithm.hash.vo.SHAEncryptType;

public class TestHash {

    public static void main(String[] args) {
        //test hmac
        String key = "sk_live_2270105ca7e207b3b3e5a56dd04c493549cef964";
        String data = "{\"event\":\"charge.success\",\"data\":{\"id\":1183164216,\"domain\":\"live\",\"status\":\"success\",\"reference\":\"210621070140pch92309406\",\"amount\":50000,\"message\":null,\"gateway_response\":\"Approved by Financial Institution\",\"paid_at\":\"2021-06-21T07:01:47.000Z\",\"created_at\":\"2021-06-21T07:01:41.000Z\",\"channel\":\"card\",\"currency\":\"NGN\",\"ip_address\":\"52.49.173.169\",\"metadata\":\"\",\"log\":null,\"fees\":400,\"fees_split\":null,\"authorization\":{\"authorization_code\":\"AUTH_jify7ej4xz\",\"bin\":\"506105\",\"last4\":\"9270\",\"exp_month\":\"06\",\"exp_year\":\"2022\",\"channel\":\"card\",\"card_type\":\"verve DEBIT\",\"bank\":\"First Bank of Nigeria\",\"country_code\":\"NG\",\"brand\":\"verve\",\"reusable\":true,\"signature\":\"SIG_KIrnvMgIz4nevoGpB22A\",\"account_name\":\"OWANIYI LAWRENCE GBENGA\"},\"customer\":{\"id\":29527446,\"first_name\":null,\"last_name\":null,\"email\":\"200908163344puid22741529@msport.com\",\"customer_code\":\"CUS_ka3zv3h6j99d2x7\",\"phone\":null,\"metadata\":null,\"risk_action\":\"default\",\"international_format_phone\":null},\"plan\":{},\"subaccount\":{},\"split\":{},\"order_id\":null,\"paidAt\":\"2021-06-21T07:01:47.000Z\",\"requested_amount\":50000,\"pos_transaction_data\":null,\"source\":{\"type\":\"api\",\"source\":\"merchant_api\",\"identifier\":null}},\"order\":null,\"business_name\":\"MSPORT\"}";
        String result = HashAlgorithmUtils.hmacHashEncryption(data, key, HMACEncryptType.HMACSHA512);
        System.out.println(result);

        //test hash
        String str = "abc123";
        String md5 = HashAlgorithmUtils.hashEncryption(str, SHAEncryptType.MD5);
        String sha1 = HashAlgorithmUtils.hashEncryption(str, SHAEncryptType.SHA1);
        String sha256 = HashAlgorithmUtils.hashEncryption(str, SHAEncryptType.SHA256);
        String sha512 = HashAlgorithmUtils.hashEncryption(str, SHAEncryptType.SHA512);
        System.out.println(md5);
        System.out.println(sha1);
        System.out.println(sha256);
        System.out.println(sha512);
    }
}