counterecryptor.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package goproxy
  2. import (
  3. "crypto/aes"
  4. "crypto/cipher"
  5. "crypto/rsa"
  6. "crypto/sha256"
  7. "crypto/x509"
  8. "errors"
  9. )
  10. type CounterEncryptorRand struct {
  11. cipher cipher.Block
  12. counter []byte
  13. rand []byte
  14. ix int
  15. }
  16. func NewCounterEncryptorRandFromKey(key interface{}, seed []byte) (r CounterEncryptorRand, err error) {
  17. var keyBytes []byte
  18. switch key := key.(type) {
  19. case *rsa.PrivateKey:
  20. keyBytes = x509.MarshalPKCS1PrivateKey(key)
  21. default:
  22. err = errors.New("only RSA keys supported")
  23. return
  24. }
  25. h := sha256.New()
  26. if r.cipher, err = aes.NewCipher(h.Sum(keyBytes)[:aes.BlockSize]); err != nil {
  27. return
  28. }
  29. r.counter = make([]byte, r.cipher.BlockSize())
  30. if seed != nil {
  31. copy(r.counter, h.Sum(seed)[:r.cipher.BlockSize()])
  32. }
  33. r.rand = make([]byte, r.cipher.BlockSize())
  34. r.ix = len(r.rand)
  35. return
  36. }
  37. func (c *CounterEncryptorRand) Seed(b []byte) {
  38. if len(b) != len(c.counter) {
  39. panic("SetCounter: wrong counter size")
  40. }
  41. copy(c.counter, b)
  42. }
  43. func (c *CounterEncryptorRand) refill() {
  44. c.cipher.Encrypt(c.rand, c.counter)
  45. for i := 0; i < len(c.counter); i++ {
  46. if c.counter[i]++; c.counter[i] != 0 {
  47. break
  48. }
  49. }
  50. c.ix = 0
  51. }
  52. func (c *CounterEncryptorRand) Read(b []byte) (n int, err error) {
  53. if c.ix == len(c.rand) {
  54. c.refill()
  55. }
  56. if n = len(c.rand) - c.ix; n > len(b) {
  57. n = len(b)
  58. }
  59. copy(b, c.rand[c.ix:c.ix+n])
  60. c.ix += n
  61. return
  62. }