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