lkcp9_entropy.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. // Copyright © 2015 Daniel Fu <daniel820313@gmail.com>.
  2. // Copyright © 2019 Loki 'l0k18' Verloren <stalker.loki@protonmail.ch>.
  3. // Copyright © 2020 Gridfinity, LLC. <admin@gridfinity.com>.
  4. // Copyright © 2020 Jeffrey H. Johnson <jeff@gridfinity.com>.
  5. //
  6. // All rights reserved.
  7. //
  8. // All use of this code is governed by the MIT license.
  9. // The complete license is available in the LICENSE file.
  10. package lkcp9 // import "go.gridfinity.dev/lkcp9"
  11. import (
  12. "crypto/aes"
  13. "crypto/cipher"
  14. "crypto/md5"
  15. "crypto/rand"
  16. "io"
  17. )
  18. // Entropy defines a entropy source
  19. type Entropy interface {
  20. Init()
  21. Fill(
  22. nonce []byte,
  23. )
  24. }
  25. type KcpNonceMD5 struct {
  26. seed [md5.Size]byte
  27. }
  28. func (
  29. n *KcpNonceMD5,
  30. ) Init() {
  31. }
  32. func (
  33. n *KcpNonceMD5,
  34. ) Fill(
  35. nonce []byte,
  36. ) {
  37. if n.seed[0] == 0 {
  38. io.ReadFull(
  39. rand.Reader,
  40. n.seed[:],
  41. )
  42. }
  43. n.seed = md5.Sum(
  44. n.seed[:],
  45. )
  46. copy(
  47. nonce,
  48. n.seed[:],
  49. )
  50. }
  51. type KcpNonceAES128 struct {
  52. seed [aes.BlockSize]byte
  53. block cipher.Block
  54. }
  55. func (
  56. n *KcpNonceAES128,
  57. ) Init() {
  58. var key [16]byte
  59. io.ReadFull(
  60. rand.Reader,
  61. key[:],
  62. )
  63. io.ReadFull(
  64. rand.Reader,
  65. n.seed[:],
  66. )
  67. block, _ := aes.NewCipher(
  68. key[:],
  69. )
  70. n.block = block
  71. }
  72. func (
  73. n *KcpNonceAES128,
  74. ) Fill(
  75. nonce []byte,
  76. ) {
  77. if n.seed[0] == 0 {
  78. io.ReadFull(
  79. rand.Reader,
  80. n.seed[:],
  81. )
  82. }
  83. n.block.Encrypt(
  84. n.seed[:],
  85. n.seed[:],
  86. )
  87. copy(
  88. nonce,
  89. n.seed[:],
  90. )
  91. }