aes.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package crypto
  2. import (
  3. "crypto/aes"
  4. "crypto/cipher"
  5. "io"
  6. )
  7. func NewAesDecryptionStream(key []byte, iv []byte) cipher.Stream {
  8. aesBlock, _ := aes.NewCipher(key)
  9. return cipher.NewCFBDecrypter(aesBlock, iv)
  10. }
  11. func NewAesEncryptionStream(key []byte, iv []byte) cipher.Stream {
  12. aesBlock, _ := aes.NewCipher(key)
  13. return cipher.NewCFBEncrypter(aesBlock, iv)
  14. }
  15. type cryptionReader struct {
  16. stream cipher.Stream
  17. reader io.Reader
  18. }
  19. func NewCryptionReader(stream cipher.Stream, reader io.Reader) io.Reader {
  20. return &cryptionReader{
  21. stream: stream,
  22. reader: reader,
  23. }
  24. }
  25. func (this *cryptionReader) Read(data []byte) (int, error) {
  26. nBytes, err := this.reader.Read(data)
  27. if nBytes > 0 {
  28. this.stream.XORKeyStream(data[:nBytes], data[:nBytes])
  29. }
  30. return nBytes, err
  31. }
  32. type cryptionWriter struct {
  33. stream cipher.Stream
  34. writer io.Writer
  35. }
  36. func NewCryptionWriter(stream cipher.Stream, writer io.Writer) io.Writer {
  37. return &cryptionWriter{
  38. stream: stream,
  39. writer: writer,
  40. }
  41. }
  42. func (this *cryptionWriter) Write(data []byte) (int, error) {
  43. this.stream.XORKeyStream(data, data)
  44. return this.writer.Write(data)
  45. }