Java—通過(guò)sign簽名認(rèn)證實(shí)現(xiàn)安全的開(kāi)放接口API

關(guān)注WC:CodingTechWork,一起學(xué)習(xí)進(jìn)步。

@[toc]

引言

??在開(kāi)發(fā)Java API時(shí),有可能需要一些安全認(rèn)證來(lái)保證API的安全性。下面,我們通過(guò)timestamp以及sign簽名認(rèn)證來(lái)實(shí)現(xiàn)基本的安全的開(kāi)發(fā)接口API。

API接口

curl {ip}:{port}/demo/test/app -X POST -H "Content-Type:application/json" -d '
{
    "appId":"app01",
    "key01": "value01",
    "key02": "value02,
    "key03": "value03",
    "sign": "77f4d9119d43c41491ab8a7c0530a618d6e0823560eb6dd028f62ae56b1ab7bb",
    "timestamp":165820977
}'

timestamp保證唯一性

通過(guò)timestamp校驗(yàn),保證約定時(shí)間內(nèi)請(qǐng)求的唯一性

shell生成timestamp

  1. shell中生成秒級(jí)timestamp
echo $(date '+%s')
  1. shell中生成毫秒級(jí)timestamp
# 通過(guò)納秒除以1000000的方式實(shí)現(xiàn)
echo $[$(date '+%s%N')/1000000]

java生成timestamp模板

// 得到秒級(jí)
long currentTimeStamp = System.currentTimeMillis() / 1000;

sign簽名認(rèn)證

實(shí)現(xiàn)方式

  1. app服務(wù)端配置對(duì)應(yīng)appSecret, 例如app123456
  2. 所有請(qǐng)求參數(shù)按照字母排序, 配裝字符串, 采用key=value并用&鏈接
  3. 添加簽名appSecret, 字符末尾加上appSecret=app123456
  4. 采用SHA-256生產(chǎn)簽名
  5. 例:
    appId=app01&params=key01=value01;key02=value02;key03=value03&appSecret=app123456

shell生成sha-256值

echo -n "appId=app01&params=key01=value01;key02=value02;key03=value03&appSecret=app123456" | sha256sum | awk '{print $1}'

結(jié)果

77f4d9119d43c41491ab8a7c0530a618d6e0823560eb6dd028f62ae56b1ab7bb

java生成sha-256模板


package com.demo.test

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

import org.apache.commons.lang.StringUtils;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class Encrypt {

    /**
     * 返回 SHA-256 串
     *
     * @param strText
     * @return
     */
    public static String SHA256(final String strText) {
        return SHA(strText, "SHA-256");
    }

    /**
     * 返回 SHA-512 串
     *
     * @param strText
     * @return
     */
    public static String SHA512(final String strText) {
        return SHA(strText, "SHA-512");
    }

    public static String MD5(final String strText) {
        return SHA(strText, "MD5");
    }

    /**
     * SHA 加密
     *
     * @param strText
     * @return
     */
    private static String SHA(final String strText, final String type) {
        String ret = null;

        if (strText != null && strText.length() > 0) {
            try {
                MessageDigest messageDigest = MessageDigest.getInstance(type);
                messageDigest.update(strText.getBytes());
                byte[] buffer = messageDigest.digest();

                StringBuffer sb = new StringBuffer();
                for (int i = 0; i < buffer.length; i++) {
                    String hex = Integer.toHexString(0xff & buffer[i]);
                    if (hex.length() == 1) {
                        sb.append('0');
                    }
                    sb.append(hex);
                }
                ret = sb.toString();
            } catch (NoSuchAlgorithmException e) {
                log.error("{} encrypt failed.{}", type, e);
            }
        }
        return ret;
    }

    /**
     * 手機(jī)號(hào)脫敏處理
     *
     * @param phone
     * @return
     */
    public static String desensitizedPhone(String phone) {
        if (StringUtils.isNotEmpty(phone)) {
            phone = phone.replaceAll("(\\w{3})\\w*(\\w{4})", "$1****$2");
        }
        return phone;
    }

    /**
     * base64加密
     *
     * @param content
     * @return
     */
    public static String base64Encoder(String content) {
        try {
            String base64encodedString = Base64.getEncoder().encodeToString(content.getBytes("utf-8"));
            return base64encodedString;
        } catch (UnsupportedEncodingException e) {
            log.error("base64Encoder failed", e);
        }
        return null;
    }
    /**
     * base64解密
     *
     * @param content
     * @return
     */
    public static String base64Decoder(String content) {
        try {
            // 解碼
            byte[] base64decodedBytes = Base64.getDecoder().decode(content);
            return new String(base64decodedBytes, "utf-8");
        } catch (UnsupportedEncodingException e) {
            log.error("base64Decoder failed", e);
        }
        return null;
    }

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容