RTB
RTB 廣告是一種實時競價廣告,針對每個廣告在有廣告位置的時候,會實時多方競爭,價格最有優(yōu)勢的廣告主會競得這次展示機會,在媒體測在拿到素材的時候,需將本次成交的價格,上報給指定的監(jiān)控服務器,這時就需要將實時價格按照指定的加密方案加密后,替換GET鏈接中的請求參數(shù)中的價格宏來上報。
官網(wǎng)
- 官方給出的源代碼有Java和C++版本,地址如下:https://code.google.com/archive/p/privatedatacommunicationprotocol/source/default/source
- 官方解釋說明中, WINNING_PRICE 主要基于SHA-1 HMAC實現(xiàn),官方文檔給的解釋都是相關偽代碼,下面將如何用Go語言實現(xiàn)
- i_key和 e_key為字符串,用于價格加密
Go Source Code
package main
/*
golang 實現(xiàn) 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)
}