敏感数据处理

校验数据合法性

当开发者通过 getUserInfo 接口或 getPhoneNumber 请求到敏感数据时,返回的 signature 字段是在小程序服务器端通过如下算法得到:

signature = sha1(`${rawData}${session_key}`)

开发者可以在自己的服务器端执行同样的算法,来校验数据是否合法

解密敏感数据

  1. 对称解密使用的算法为 AES-128-CBC,数据采用 PKCS#7 填充
  2. 对称解密的目标密文为 encryptedData
  3. 对称解密秘钥 aeskey = Base64_Decode(session_key), aeskey 长度为 16Byte
  4. 对称解密算法初始向量为 Base64_Decode(iv)

解密敏感数据代码示例

// Node.js
const crypto = require("crypto");

function decrypt(encryptedData, sessionKey, iv) {
  const decipher = crypto.createDecipheriv(
    "aes-128-cbc",
    Buffer.from(sessionKey, "base64"),
    Buffer.from(iv, "base64")
  );
  let ret = decipher.update(encryptedData, "base64");
  ret += decipher.final();
  return ret;
}
// Go
func decrypt(encryptedData, sesseionkey, iv string) string {
	src, _ := base64.StdEncoding.DecodeString(encryptedData)
	_key, _ := base64.StdEncoding.DecodeString(sessionKey)
	_iv, _ := base64.StdEncoding.DecodeString(iv)

	block, _ := aes.NewCipher(_key)
	mode := cipher.NewCBCDecrypter(block, _iv)
	dst := make([]byte, len(src))
	mode.CryptBlocks(dst, src)
	return string(dst)
}
# python
import base64

# https://www.pycryptodome.org/
# pip install pycryptodome
from Crypto.Cipher import AES


def decrypt(encrypted_data, session_key, iv):
    data = base64.b64decode(encrypted_data)
    _key = base64.b64decode(session_key)
    _iv = base64.b64decode(iv)

    cipher = AES.new(_key, AES.MODE_CBC, _iv)
    return cipher.decrypt(data)
// Java
package com.bytedance;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

public class Decrypt {
    public static String decrypt(String encryptedData, String sessionKey, String iv) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        Base64.Decoder decoder = Base64.getDecoder();
        byte[] sessionKeyBytes = decoder.decode(sessionKey);
        byte[] ivBytes = decoder.decode(iv);
        byte[] encryptedBytes = decoder.decode(encryptedData);

        // JDK does not support PKCS7Padding, use PKCS5Padding instead
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKeySpec skeySpec = new SecretKeySpec(sessionKeyBytes, "AES");
        IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
        cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivSpec);
        byte[] ret = cipher.doFinal(encryptedBytes);
        return new String(ret);
    }
}
点击纠错