rlpx.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  1. package p2p
  2. import (
  3. "bytes"
  4. "crypto/aes"
  5. "crypto/cipher"
  6. "crypto/ecdsa"
  7. "crypto/elliptic"
  8. "crypto/hmac"
  9. "crypto/rand"
  10. "errors"
  11. "fmt"
  12. "hash"
  13. "io"
  14. "net"
  15. "sync"
  16. "time"
  17. "github.com/ethereum/go-ethereum/crypto"
  18. "github.com/ethereum/go-ethereum/crypto/ecies"
  19. "github.com/ethereum/go-ethereum/crypto/secp256k1"
  20. "github.com/ethereum/go-ethereum/crypto/sha3"
  21. "github.com/ethereum/go-ethereum/p2p/discover"
  22. "github.com/ethereum/go-ethereum/rlp"
  23. )
  24. const (
  25. maxUint24 = ^uint32(0) >> 8
  26. sskLen = 16 // ecies.MaxSharedKeyLength(pubKey) / 2
  27. sigLen = 65 // elliptic S256
  28. pubLen = 64 // 512 bit pubkey in uncompressed representation without format byte
  29. shaLen = 32 // hash length (for nonce etc)
  30. authMsgLen = sigLen + shaLen + pubLen + shaLen + 1
  31. authRespLen = pubLen + shaLen + 1
  32. eciesBytes = 65 + 16 + 32
  33. encAuthMsgLen = authMsgLen + eciesBytes // size of the final ECIES payload sent as initiator's handshake
  34. encAuthRespLen = authRespLen + eciesBytes // size of the final ECIES payload sent as receiver's handshake
  35. // total timeout for encryption handshake and protocol
  36. // handshake in both directions.
  37. handshakeTimeout = 5 * time.Second
  38. // This is the timeout for sending the disconnect reason.
  39. // This is shorter than the usual timeout because we don't want
  40. // to wait if the connection is known to be bad anyway.
  41. discWriteTimeout = 1 * time.Second
  42. )
  43. // rlpx is the transport protocol used by actual (non-test) connections.
  44. // It wraps the frame encoder with locks and read/write deadlines.
  45. type rlpx struct {
  46. fd net.Conn
  47. rmu, wmu sync.Mutex
  48. rw *rlpxFrameRW
  49. }
  50. func newRLPX(fd net.Conn) transport {
  51. fd.SetDeadline(time.Now().Add(handshakeTimeout))
  52. return &rlpx{fd: fd}
  53. }
  54. func (t *rlpx) ReadMsg() (Msg, error) {
  55. t.rmu.Lock()
  56. defer t.rmu.Unlock()
  57. t.fd.SetReadDeadline(time.Now().Add(frameReadTimeout))
  58. return t.rw.ReadMsg()
  59. }
  60. func (t *rlpx) WriteMsg(msg Msg) error {
  61. t.wmu.Lock()
  62. defer t.wmu.Unlock()
  63. t.fd.SetWriteDeadline(time.Now().Add(frameWriteTimeout))
  64. return t.rw.WriteMsg(msg)
  65. }
  66. func (t *rlpx) close(err error) {
  67. t.wmu.Lock()
  68. defer t.wmu.Unlock()
  69. // Tell the remote end why we're disconnecting if possible.
  70. if t.rw != nil {
  71. if r, ok := err.(DiscReason); ok && r != DiscNetworkError {
  72. t.fd.SetWriteDeadline(time.Now().Add(discWriteTimeout))
  73. SendItems(t.rw, discMsg, r)
  74. }
  75. }
  76. t.fd.Close()
  77. }
  78. // doEncHandshake runs the protocol handshake using authenticated
  79. // messages. the protocol handshake is the first authenticated message
  80. // and also verifies whether the encryption handshake 'worked' and the
  81. // remote side actually provided the right public key.
  82. func (t *rlpx) doProtoHandshake(our *protoHandshake) (their *protoHandshake, err error) {
  83. // Writing our handshake happens concurrently, we prefer
  84. // returning the handshake read error. If the remote side
  85. // disconnects us early with a valid reason, we should return it
  86. // as the error so it can be tracked elsewhere.
  87. werr := make(chan error, 1)
  88. go func() { werr <- Send(t.rw, handshakeMsg, our) }()
  89. if their, err = readProtocolHandshake(t.rw, our); err != nil {
  90. return nil, err
  91. }
  92. if err := <-werr; err != nil {
  93. return nil, fmt.Errorf("write error: %v", err)
  94. }
  95. return their, nil
  96. }
  97. func readProtocolHandshake(rw MsgReader, our *protoHandshake) (*protoHandshake, error) {
  98. msg, err := rw.ReadMsg()
  99. if err != nil {
  100. return nil, err
  101. }
  102. if msg.Size > baseProtocolMaxMsgSize {
  103. return nil, fmt.Errorf("message too big")
  104. }
  105. if msg.Code == discMsg {
  106. // Disconnect before protocol handshake is valid according to the
  107. // spec and we send it ourself if the posthanshake checks fail.
  108. // We can't return the reason directly, though, because it is echoed
  109. // back otherwise. Wrap it in a string instead.
  110. var reason [1]DiscReason
  111. rlp.Decode(msg.Payload, &reason)
  112. return nil, reason[0]
  113. }
  114. if msg.Code != handshakeMsg {
  115. return nil, fmt.Errorf("expected handshake, got %x", msg.Code)
  116. }
  117. var hs protoHandshake
  118. if err := msg.Decode(&hs); err != nil {
  119. return nil, err
  120. }
  121. // validate handshake info
  122. if hs.Version != our.Version {
  123. return nil, DiscIncompatibleVersion
  124. }
  125. if (hs.ID == discover.NodeID{}) {
  126. return nil, DiscInvalidIdentity
  127. }
  128. return &hs, nil
  129. }
  130. func (t *rlpx) doEncHandshake(prv *ecdsa.PrivateKey, dial *discover.Node) (discover.NodeID, error) {
  131. var (
  132. sec secrets
  133. err error
  134. )
  135. if dial == nil {
  136. sec, err = receiverEncHandshake(t.fd, prv, nil)
  137. } else {
  138. sec, err = initiatorEncHandshake(t.fd, prv, dial.ID, nil)
  139. }
  140. if err != nil {
  141. return discover.NodeID{}, err
  142. }
  143. t.wmu.Lock()
  144. t.rw = newRLPXFrameRW(t.fd, sec)
  145. t.wmu.Unlock()
  146. return sec.RemoteID, nil
  147. }
  148. // encHandshake contains the state of the encryption handshake.
  149. type encHandshake struct {
  150. initiator bool
  151. remoteID discover.NodeID
  152. remotePub *ecies.PublicKey // remote-pubk
  153. initNonce, respNonce []byte // nonce
  154. randomPrivKey *ecies.PrivateKey // ecdhe-random
  155. remoteRandomPub *ecies.PublicKey // ecdhe-random-pubk
  156. }
  157. // secrets represents the connection secrets
  158. // which are negotiated during the encryption handshake.
  159. type secrets struct {
  160. RemoteID discover.NodeID
  161. AES, MAC []byte
  162. EgressMAC, IngressMAC hash.Hash
  163. Token []byte
  164. }
  165. // secrets is called after the handshake is completed.
  166. // It extracts the connection secrets from the handshake values.
  167. func (h *encHandshake) secrets(auth, authResp []byte) (secrets, error) {
  168. ecdheSecret, err := h.randomPrivKey.GenerateShared(h.remoteRandomPub, sskLen, sskLen)
  169. if err != nil {
  170. return secrets{}, err
  171. }
  172. // derive base secrets from ephemeral key agreement
  173. sharedSecret := crypto.Sha3(ecdheSecret, crypto.Sha3(h.respNonce, h.initNonce))
  174. aesSecret := crypto.Sha3(ecdheSecret, sharedSecret)
  175. s := secrets{
  176. RemoteID: h.remoteID,
  177. AES: aesSecret,
  178. MAC: crypto.Sha3(ecdheSecret, aesSecret),
  179. Token: crypto.Sha3(sharedSecret),
  180. }
  181. // setup sha3 instances for the MACs
  182. mac1 := sha3.NewKeccak256()
  183. mac1.Write(xor(s.MAC, h.respNonce))
  184. mac1.Write(auth)
  185. mac2 := sha3.NewKeccak256()
  186. mac2.Write(xor(s.MAC, h.initNonce))
  187. mac2.Write(authResp)
  188. if h.initiator {
  189. s.EgressMAC, s.IngressMAC = mac1, mac2
  190. } else {
  191. s.EgressMAC, s.IngressMAC = mac2, mac1
  192. }
  193. return s, nil
  194. }
  195. func (h *encHandshake) ecdhShared(prv *ecdsa.PrivateKey) ([]byte, error) {
  196. return ecies.ImportECDSA(prv).GenerateShared(h.remotePub, sskLen, sskLen)
  197. }
  198. // initiatorEncHandshake negotiates a session token on conn.
  199. // it should be called on the dialing side of the connection.
  200. //
  201. // prv is the local client's private key.
  202. // token is the token from a previous session with this node.
  203. func initiatorEncHandshake(conn io.ReadWriter, prv *ecdsa.PrivateKey, remoteID discover.NodeID, token []byte) (s secrets, err error) {
  204. h, err := newInitiatorHandshake(remoteID)
  205. if err != nil {
  206. return s, err
  207. }
  208. auth, err := h.authMsg(prv, token)
  209. if err != nil {
  210. return s, err
  211. }
  212. if _, err = conn.Write(auth); err != nil {
  213. return s, err
  214. }
  215. response := make([]byte, encAuthRespLen)
  216. if _, err = io.ReadFull(conn, response); err != nil {
  217. return s, err
  218. }
  219. if err := h.decodeAuthResp(response, prv); err != nil {
  220. return s, err
  221. }
  222. return h.secrets(auth, response)
  223. }
  224. func newInitiatorHandshake(remoteID discover.NodeID) (*encHandshake, error) {
  225. // generate random initiator nonce
  226. n := make([]byte, shaLen)
  227. if _, err := rand.Read(n); err != nil {
  228. return nil, err
  229. }
  230. // generate random keypair to use for signing
  231. randpriv, err := ecies.GenerateKey(rand.Reader, crypto.S256(), nil)
  232. if err != nil {
  233. return nil, err
  234. }
  235. rpub, err := remoteID.Pubkey()
  236. if err != nil {
  237. return nil, fmt.Errorf("bad remoteID: %v", err)
  238. }
  239. h := &encHandshake{
  240. initiator: true,
  241. remoteID: remoteID,
  242. remotePub: ecies.ImportECDSAPublic(rpub),
  243. initNonce: n,
  244. randomPrivKey: randpriv,
  245. }
  246. return h, nil
  247. }
  248. // authMsg creates an encrypted initiator handshake message.
  249. func (h *encHandshake) authMsg(prv *ecdsa.PrivateKey, token []byte) ([]byte, error) {
  250. var tokenFlag byte
  251. if token == nil {
  252. // no session token found means we need to generate shared secret.
  253. // ecies shared secret is used as initial session token for new peers
  254. // generate shared key from prv and remote pubkey
  255. var err error
  256. if token, err = h.ecdhShared(prv); err != nil {
  257. return nil, err
  258. }
  259. } else {
  260. // for known peers, we use stored token from the previous session
  261. tokenFlag = 0x01
  262. }
  263. // sign known message:
  264. // ecdh-shared-secret^nonce for new peers
  265. // token^nonce for old peers
  266. signed := xor(token, h.initNonce)
  267. signature, err := crypto.Sign(signed, h.randomPrivKey.ExportECDSA())
  268. if err != nil {
  269. return nil, err
  270. }
  271. // encode auth message
  272. // signature || sha3(ecdhe-random-pubk) || pubk || nonce || token-flag
  273. msg := make([]byte, authMsgLen)
  274. n := copy(msg, signature)
  275. n += copy(msg[n:], crypto.Sha3(exportPubkey(&h.randomPrivKey.PublicKey)))
  276. n += copy(msg[n:], crypto.FromECDSAPub(&prv.PublicKey)[1:])
  277. n += copy(msg[n:], h.initNonce)
  278. msg[n] = tokenFlag
  279. // encrypt auth message using remote-pubk
  280. return ecies.Encrypt(rand.Reader, h.remotePub, msg, nil, nil)
  281. }
  282. // decodeAuthResp decode an encrypted authentication response message.
  283. func (h *encHandshake) decodeAuthResp(auth []byte, prv *ecdsa.PrivateKey) error {
  284. msg, err := crypto.Decrypt(prv, auth)
  285. if err != nil {
  286. return fmt.Errorf("could not decrypt auth response (%v)", err)
  287. }
  288. h.respNonce = msg[pubLen : pubLen+shaLen]
  289. h.remoteRandomPub, err = importPublicKey(msg[:pubLen])
  290. if err != nil {
  291. return err
  292. }
  293. // ignore token flag for now
  294. return nil
  295. }
  296. // receiverEncHandshake negotiates a session token on conn.
  297. // it should be called on the listening side of the connection.
  298. //
  299. // prv is the local client's private key.
  300. // token is the token from a previous session with this node.
  301. func receiverEncHandshake(conn io.ReadWriter, prv *ecdsa.PrivateKey, token []byte) (s secrets, err error) {
  302. // read remote auth sent by initiator.
  303. auth := make([]byte, encAuthMsgLen)
  304. if _, err := io.ReadFull(conn, auth); err != nil {
  305. return s, err
  306. }
  307. h, err := decodeAuthMsg(prv, token, auth)
  308. if err != nil {
  309. return s, err
  310. }
  311. // send auth response
  312. resp, err := h.authResp(prv, token)
  313. if err != nil {
  314. return s, err
  315. }
  316. if _, err = conn.Write(resp); err != nil {
  317. return s, err
  318. }
  319. return h.secrets(auth, resp)
  320. }
  321. func decodeAuthMsg(prv *ecdsa.PrivateKey, token []byte, auth []byte) (*encHandshake, error) {
  322. var err error
  323. h := new(encHandshake)
  324. // generate random keypair for session
  325. h.randomPrivKey, err = ecies.GenerateKey(rand.Reader, crypto.S256(), nil)
  326. if err != nil {
  327. return nil, err
  328. }
  329. // generate random nonce
  330. h.respNonce = make([]byte, shaLen)
  331. if _, err = rand.Read(h.respNonce); err != nil {
  332. return nil, err
  333. }
  334. msg, err := crypto.Decrypt(prv, auth)
  335. if err != nil {
  336. return nil, fmt.Errorf("could not decrypt auth message (%v)", err)
  337. }
  338. // decode message parameters
  339. // signature || sha3(ecdhe-random-pubk) || pubk || nonce || token-flag
  340. h.initNonce = msg[authMsgLen-shaLen-1 : authMsgLen-1]
  341. copy(h.remoteID[:], msg[sigLen+shaLen:sigLen+shaLen+pubLen])
  342. rpub, err := h.remoteID.Pubkey()
  343. if err != nil {
  344. return nil, fmt.Errorf("bad remoteID: %#v", err)
  345. }
  346. h.remotePub = ecies.ImportECDSAPublic(rpub)
  347. // recover remote random pubkey from signed message.
  348. if token == nil {
  349. // TODO: it is an error if the initiator has a token and we don't. check that.
  350. // no session token means we need to generate shared secret.
  351. // ecies shared secret is used as initial session token for new peers.
  352. // generate shared key from prv and remote pubkey.
  353. if token, err = h.ecdhShared(prv); err != nil {
  354. return nil, err
  355. }
  356. }
  357. signedMsg := xor(token, h.initNonce)
  358. remoteRandomPub, err := secp256k1.RecoverPubkey(signedMsg, msg[:sigLen])
  359. if err != nil {
  360. return nil, err
  361. }
  362. h.remoteRandomPub, _ = importPublicKey(remoteRandomPub)
  363. return h, nil
  364. }
  365. // authResp generates the encrypted authentication response message.
  366. func (h *encHandshake) authResp(prv *ecdsa.PrivateKey, token []byte) ([]byte, error) {
  367. // responder auth message
  368. // E(remote-pubk, ecdhe-random-pubk || nonce || 0x0)
  369. resp := make([]byte, authRespLen)
  370. n := copy(resp, exportPubkey(&h.randomPrivKey.PublicKey))
  371. n += copy(resp[n:], h.respNonce)
  372. if token == nil {
  373. resp[n] = 0
  374. } else {
  375. resp[n] = 1
  376. }
  377. // encrypt using remote-pubk
  378. return ecies.Encrypt(rand.Reader, h.remotePub, resp, nil, nil)
  379. }
  380. // importPublicKey unmarshals 512 bit public keys.
  381. func importPublicKey(pubKey []byte) (*ecies.PublicKey, error) {
  382. var pubKey65 []byte
  383. switch len(pubKey) {
  384. case 64:
  385. // add 'uncompressed key' flag
  386. pubKey65 = append([]byte{0x04}, pubKey...)
  387. case 65:
  388. pubKey65 = pubKey
  389. default:
  390. return nil, fmt.Errorf("invalid public key length %v (expect 64/65)", len(pubKey))
  391. }
  392. // TODO: fewer pointless conversions
  393. return ecies.ImportECDSAPublic(crypto.ToECDSAPub(pubKey65)), nil
  394. }
  395. func exportPubkey(pub *ecies.PublicKey) []byte {
  396. if pub == nil {
  397. panic("nil pubkey")
  398. }
  399. return elliptic.Marshal(pub.Curve, pub.X, pub.Y)[1:]
  400. }
  401. func xor(one, other []byte) (xor []byte) {
  402. xor = make([]byte, len(one))
  403. for i := 0; i < len(one); i++ {
  404. xor[i] = one[i] ^ other[i]
  405. }
  406. return xor
  407. }
  408. var (
  409. // this is used in place of actual frame header data.
  410. // TODO: replace this when Msg contains the protocol type code.
  411. zeroHeader = []byte{0xC2, 0x80, 0x80}
  412. // sixteen zero bytes
  413. zero16 = make([]byte, 16)
  414. )
  415. // rlpxFrameRW implements a simplified version of RLPx framing.
  416. // chunked messages are not supported and all headers are equal to
  417. // zeroHeader.
  418. //
  419. // rlpxFrameRW is not safe for concurrent use from multiple goroutines.
  420. type rlpxFrameRW struct {
  421. conn io.ReadWriter
  422. enc cipher.Stream
  423. dec cipher.Stream
  424. macCipher cipher.Block
  425. egressMAC hash.Hash
  426. ingressMAC hash.Hash
  427. }
  428. func newRLPXFrameRW(conn io.ReadWriter, s secrets) *rlpxFrameRW {
  429. macc, err := aes.NewCipher(s.MAC)
  430. if err != nil {
  431. panic("invalid MAC secret: " + err.Error())
  432. }
  433. encc, err := aes.NewCipher(s.AES)
  434. if err != nil {
  435. panic("invalid AES secret: " + err.Error())
  436. }
  437. // we use an all-zeroes IV for AES because the key used
  438. // for encryption is ephemeral.
  439. iv := make([]byte, encc.BlockSize())
  440. return &rlpxFrameRW{
  441. conn: conn,
  442. enc: cipher.NewCTR(encc, iv),
  443. dec: cipher.NewCTR(encc, iv),
  444. macCipher: macc,
  445. egressMAC: s.EgressMAC,
  446. ingressMAC: s.IngressMAC,
  447. }
  448. }
  449. func (rw *rlpxFrameRW) WriteMsg(msg Msg) error {
  450. ptype, _ := rlp.EncodeToBytes(msg.Code)
  451. // write header
  452. headbuf := make([]byte, 32)
  453. fsize := uint32(len(ptype)) + msg.Size
  454. if fsize > maxUint24 {
  455. return errors.New("message size overflows uint24")
  456. }
  457. putInt24(fsize, headbuf) // TODO: check overflow
  458. copy(headbuf[3:], zeroHeader)
  459. rw.enc.XORKeyStream(headbuf[:16], headbuf[:16]) // first half is now encrypted
  460. // write header MAC
  461. copy(headbuf[16:], updateMAC(rw.egressMAC, rw.macCipher, headbuf[:16]))
  462. if _, err := rw.conn.Write(headbuf); err != nil {
  463. return err
  464. }
  465. // write encrypted frame, updating the egress MAC hash with
  466. // the data written to conn.
  467. tee := cipher.StreamWriter{S: rw.enc, W: io.MultiWriter(rw.conn, rw.egressMAC)}
  468. if _, err := tee.Write(ptype); err != nil {
  469. return err
  470. }
  471. if _, err := io.Copy(tee, msg.Payload); err != nil {
  472. return err
  473. }
  474. if padding := fsize % 16; padding > 0 {
  475. if _, err := tee.Write(zero16[:16-padding]); err != nil {
  476. return err
  477. }
  478. }
  479. // write frame MAC. egress MAC hash is up to date because
  480. // frame content was written to it as well.
  481. fmacseed := rw.egressMAC.Sum(nil)
  482. mac := updateMAC(rw.egressMAC, rw.macCipher, fmacseed)
  483. _, err := rw.conn.Write(mac)
  484. return err
  485. }
  486. func (rw *rlpxFrameRW) ReadMsg() (msg Msg, err error) {
  487. // read the header
  488. headbuf := make([]byte, 32)
  489. if _, err := io.ReadFull(rw.conn, headbuf); err != nil {
  490. return msg, err
  491. }
  492. // verify header mac
  493. shouldMAC := updateMAC(rw.ingressMAC, rw.macCipher, headbuf[:16])
  494. if !hmac.Equal(shouldMAC, headbuf[16:]) {
  495. return msg, errors.New("bad header MAC")
  496. }
  497. rw.dec.XORKeyStream(headbuf[:16], headbuf[:16]) // first half is now decrypted
  498. fsize := readInt24(headbuf)
  499. // ignore protocol type for now
  500. // read the frame content
  501. var rsize = fsize // frame size rounded up to 16 byte boundary
  502. if padding := fsize % 16; padding > 0 {
  503. rsize += 16 - padding
  504. }
  505. framebuf := make([]byte, rsize)
  506. if _, err := io.ReadFull(rw.conn, framebuf); err != nil {
  507. return msg, err
  508. }
  509. // read and validate frame MAC. we can re-use headbuf for that.
  510. rw.ingressMAC.Write(framebuf)
  511. fmacseed := rw.ingressMAC.Sum(nil)
  512. if _, err := io.ReadFull(rw.conn, headbuf[:16]); err != nil {
  513. return msg, err
  514. }
  515. shouldMAC = updateMAC(rw.ingressMAC, rw.macCipher, fmacseed)
  516. if !hmac.Equal(shouldMAC, headbuf[:16]) {
  517. return msg, errors.New("bad frame MAC")
  518. }
  519. // decrypt frame content
  520. rw.dec.XORKeyStream(framebuf, framebuf)
  521. // decode message code
  522. content := bytes.NewReader(framebuf[:fsize])
  523. if err := rlp.Decode(content, &msg.Code); err != nil {
  524. return msg, err
  525. }
  526. msg.Size = uint32(content.Len())
  527. msg.Payload = content
  528. return msg, nil
  529. }
  530. // updateMAC reseeds the given hash with encrypted seed.
  531. // it returns the first 16 bytes of the hash sum after seeding.
  532. func updateMAC(mac hash.Hash, block cipher.Block, seed []byte) []byte {
  533. aesbuf := make([]byte, aes.BlockSize)
  534. block.Encrypt(aesbuf, mac.Sum(nil))
  535. for i := range aesbuf {
  536. aesbuf[i] ^= seed[i]
  537. }
  538. mac.Write(aesbuf)
  539. return mac.Sum(nil)[:16]
  540. }
  541. func readInt24(b []byte) uint32 {
  542. return uint32(b[2]) | uint32(b[1])<<8 | uint32(b[0])<<16
  543. }
  544. func putInt24(v uint32, b []byte) {
  545. b[0] = byte(v >> 16)
  546. b[1] = byte(v >> 8)
  547. b[2] = byte(v)
  548. }