aes_ctr.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package osscrypto
  2. import (
  3. "crypto/aes"
  4. "crypto/cipher"
  5. "io"
  6. )
  7. type aesCtr struct {
  8. encrypter cipher.Stream
  9. decrypter cipher.Stream
  10. }
  11. func newAesCtr(cd CipherData) (Cipher, error) {
  12. block, err := aes.NewCipher(cd.Key)
  13. if err != nil {
  14. return nil, err
  15. }
  16. encrypter := cipher.NewCTR(block, cd.IV)
  17. decrypter := cipher.NewCTR(block, cd.IV)
  18. return &aesCtr{encrypter, decrypter}, nil
  19. }
  20. func (c *aesCtr) Encrypt(src io.Reader) io.Reader {
  21. reader := &ctrEncryptReader{
  22. encrypter: c.encrypter,
  23. src: src,
  24. }
  25. return reader
  26. }
  27. type ctrEncryptReader struct {
  28. encrypter cipher.Stream
  29. src io.Reader
  30. }
  31. func (reader *ctrEncryptReader) Read(data []byte) (int, error) {
  32. plainText := make([]byte, len(data), len(data))
  33. n, err := reader.src.Read(plainText)
  34. if n > 0 {
  35. plainText = plainText[0:n]
  36. reader.encrypter.XORKeyStream(data, plainText)
  37. }
  38. return n, err
  39. }
  40. func (c *aesCtr) Decrypt(src io.Reader) io.Reader {
  41. return &ctrDecryptReader{
  42. decrypter: c.decrypter,
  43. src: src,
  44. }
  45. }
  46. type ctrDecryptReader struct {
  47. decrypter cipher.Stream
  48. src io.Reader
  49. }
  50. func (reader *ctrDecryptReader) Read(data []byte) (int, error) {
  51. cryptoText := make([]byte, len(data), len(data))
  52. n, err := reader.src.Read(cryptoText)
  53. if n > 0 {
  54. cryptoText = cryptoText[0:n]
  55. reader.decrypter.XORKeyStream(data, cryptoText)
  56. }
  57. return n, err
  58. }