RTB
RTB 广告是一种实时竞价广告,针对每个广告在有广告位置的时候,会实时多方竞争,价格最有优势的广告主会竞得这次展示机会,在媒体测在拿到素材的时候,需将本次成交的价格,上报给指定的监控服务器,这时就需要将实时价格按照指定的加密方案加密后,替换GET链接中的请求参数中的价格宏来上报。
官网
- 官方给出的源代码有Java和C++版本,地址如下:https://code.google.com/archive/p/privatedatacommunicationprotocol/source/default/source
- 官方解释说明中, WINNING_PRICE 主要基于SHA-1 HMAC实现,官方文档给的解释都是相关伪代码,下面将如何用Go语言实现
- i_key和 e_key为字符串,用于价格加密
Go Source Code
package main
/*
golang 实现 google 的rtb 价格加密方案
https://developers.google.com/authorized-buyers/rtb/response-guide/decrypt-price#encryption-scheme
*/
import (
"crypto/hmac"
"crypto/md5"
"crypto/sha1"
"encoding/base64"
"encoding/binary"
"encoding/hex"
"fmt"
"hash"
"math"
"strings"
)
const (
PayloadSize = 8
InitVectorSize = 16
SignatureSize = 4
EKey = ""
IKey = ""
UTF8 = "utf-8"
)
func AddBase64Padding(paramBase64 string) string {
if i := len(paramBase64) % 4; i != 0 {
paramBase64 += strings.Repeat("=", 4-i)
}
return paramBase64
}
func CreateHmac(key, mode string, isBase64 bool) (hash.Hash, error) {
var b64DecodedKey, k []byte
var err error
if isBase64 {
b64DecodedKey, err = base64.URLEncoding.DecodeString(AddBase64Padding(key))
if err == nil {
key = string(b64DecodedKey[:])
}
}
if mode == UTF8 {
k = []byte(key)
} else {
k, err = hex.DecodeString(key)
}
if err != nil {
return nil, err
}
return hmac.New(sha1.New, k), nil
}
func HmacSum(hmacParam hash.Hash, buf []byte) []byte {
hmacParam.Reset()
hmacParam.Write(buf)
return hmacParam.Sum(nil)
}
func GenerateHmac(key string, buf []byte) ([]byte, error) {
hmacParam, err := CreateHmac(key, UTF8, true)
if err != nil {
err = fmt.Errorf("jzt/encrypt: create hmac error, %s", err.Error())
return nil, err
}
return HmacSum(hmacParam, buf), nil
}
func EncryptPrice(price float64) (string, error) {
var (
iv = make([]byte, InitVectorSize)
encoded = make([]byte, PayloadSize)
signature = make([]byte, SignatureSize)
priceBytes = make([]byte, PayloadSize)
)
sum := md5.Sum([]byte(""))
copy(iv[:], sum[:])
// pad = hmac(e_key, iv) // first 8 bytes
pad, err := GenerateHmac(EKey, iv[:])
if err != nil {
return "", err
}
pad = pad[:PayloadSize]
bits := math.Float64bits(price)
binary.BigEndian.PutUint64(priceBytes, bits)
// enc_price = pad <xor> price
for i := range priceBytes {
encoded[i] = pad[i] ^ priceBytes[i]
}
// signature = hmac(i_key, data || iv), first 4 bytes
sig, err := GenerateHmac(IKey, append(priceBytes[:], iv[:]...))
if err != nil {
return "", err
}
signature = sig[:SignatureSize]
// final_message = WebSafeBase64Encode( iv || enc_price || signature )
finalMessage := strings.TrimRight(
base64.URLEncoding.EncodeToString(append(append(iv[:], encoded[:]...), signature[:]...)),
"=")
return finalMessage, nil
}
func DecryptPrice(finalMessage string) (float64, error) {
var err error
var errPrice float64
encryptedPrice := AddBase64Padding(finalMessage)
decoded, err := base64.URLEncoding.DecodeString(encryptedPrice)
if err != nil {
return errPrice, err
}
var (
iv = make([]byte, InitVectorSize)
p = make([]byte, PayloadSize)
signature = make([]byte, SignatureSize)
priceBytes = make([]byte, PayloadSize)
)
copy(iv[:], decoded[0:16])
copy(p[:], decoded[16:24])
copy(signature[:], decoded[24:28])
pad, err := GenerateHmac(EKey, iv[:])
if err != nil {
return errPrice, err
}
pad = pad[:PayloadSize]
for i := range p {
priceBytes[i] = pad[i] ^ p[i]
}
sig, err := GenerateHmac(IKey, append(priceBytes[:], iv[:]...))
if err != nil {
return errPrice, err
}
sig = sig[:SignatureSize]
for i := range sig {
if sig[i] != signature[i] {
return errPrice, fmt.Errorf("jzt/decrypt: Failed to decrypt, got:%s ,expect:%s", string(sig), string(signature))
}
}
price := math.Float64frombits(binary.BigEndian.Uint64(priceBytes))
return price, nil
}
func main() {
result, err := EncryptPrice(0.11)
if err != nil {
err = fmt.Errorf("Encryption failed. Error : %s", err)
return
}
fmt.Println(result)
price, err := DecryptPrice("1B2M2Y8AsgTpgAmY7PhCfumh5TxN_8-DUn4uHg")
if err != nil {
err = fmt.Errorf("Encryption failed. Error : %s", err)
return
}
fmt.Println(price)
}
有疑问加站长微信联系(非本文作者)