package crypto
import (
"crypto/sha256"
"github.com/gotd/td/bin"
)
type Side byte
const (
Client Side = 0
Server Side = 1
)
func (s Side ) DecryptSide () Side {
return s ^ 1
}
func getX (mode Side ) int {
switch mode {
case Client :
return 0
case Server :
return 8
default :
return 0
}
}
func msgKeyLarge (r []byte , authKey Key , plaintextPadded []byte , mode Side ) []byte {
h := sha256 .New ()
x := getX (mode )
_, _ = h .Write (authKey [88 +x : 32 +88 +x ])
_, _ = h .Write (plaintextPadded )
return h .Sum (r )
}
func messageKey (messageKeyLarge []byte ) (v bin .Int128 ) {
b := messageKeyLarge [8 : 16 +8 ]
copy (v [:len (b )], b )
return v
}
func sha256a (r []byte , authKey *Key , msgKey *bin .Int128 , x int ) []byte {
h := sha256 .New ()
_, _ = h .Write (msgKey [:])
_, _ = h .Write (authKey [x : x +36 ])
return h .Sum (r )
}
func sha256b (r []byte , authKey *Key , msgKey *bin .Int128 , x int ) []byte {
h := sha256 .New ()
_, _ = h .Write (authKey [40 +x : 40 +x +36 ])
_, _ = h .Write (msgKey [:])
return h .Sum (r )
}
func aesKey (sha256a , sha256b []byte , v *bin .Int256 ) {
copy (v [:8 ], sha256a [:8 ])
copy (v [8 :], sha256b [8 :16 +8 ])
copy (v [24 :], sha256a [24 :24 +8 ])
}
func aesIV (sha256a , sha256b []byte , v *bin .Int256 ) {
aesKey (sha256b , sha256a , v )
}
func Keys (authKey Key , msgKey bin .Int128 , mode Side ) (key , iv bin .Int256 ) {
x := getX (mode )
r := make ([]byte , 512 )
a := sha256a (r [0 :0 ], &authKey , &msgKey , x )
b := sha256b (r [256 :256 ], &authKey , &msgKey , x )
aesKey (a , b , &key )
aesIV (a , b , &iv )
return key , iv
}
func MessageKey (authKey Key , plaintextPadded []byte , mode Side ) bin .Int128 {
r := make ([]byte , 0 , 256 )
msgKeyLarge := msgKeyLarge (r , authKey , plaintextPadded , mode )
return messageKey (msgKeyLarge )
}
The pages are generated with Golds v0.6.7 . (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu .
PR and bug reports are welcome and can be submitted to the issue list .
Please follow @Go100and1 (reachable from the left QR code) to get the latest news of Golds .