counterecryptor.go 1.5 KB

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