zzc.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /*
  2. * Copyright (c) 2000-2018, 达梦数据库有限公司.
  3. * All rights reserved.
  4. */
  5. // go官方没有实现ecb加密模式
  6. package security
  7. import (
  8. "crypto/cipher"
  9. )
  10. type ecb struct {
  11. b cipher.Block
  12. blockSize int
  13. }
  14. func newECB(b cipher.Block) *ecb {
  15. return &ecb{
  16. b: b,
  17. blockSize: b.BlockSize(),
  18. }
  19. }
  20. type ecbEncrypter ecb
  21. func NewECBEncrypter(b cipher.Block) cipher.BlockMode {
  22. return (*ecbEncrypter)(newECB(b))
  23. }
  24. func (x *ecbEncrypter) BlockSize() int { return x.blockSize }
  25. func (x *ecbEncrypter) CryptBlocks(dst, src []byte) {
  26. if len(src)%x.blockSize != 0 {
  27. panic("dm/security: input not full blocks")
  28. }
  29. if len(dst) < len(src) {
  30. panic("dm/security: output smaller than input")
  31. }
  32. if InexactOverlap(dst[:len(src)], src) {
  33. panic("dm/security: invalid buffer overlap")
  34. }
  35. for bs, be := 0, x.blockSize; bs < len(src); bs, be = bs+x.blockSize, be+x.blockSize {
  36. x.b.Encrypt(dst[bs:be], src[bs:be])
  37. }
  38. }
  39. type ecbDecrypter ecb
  40. func NewECBDecrypter(b cipher.Block) cipher.BlockMode {
  41. return (*ecbDecrypter)(newECB(b))
  42. }
  43. func (x *ecbDecrypter) BlockSize() int { return x.blockSize }
  44. func (x *ecbDecrypter) CryptBlocks(dst, src []byte) {
  45. if len(src)%x.blockSize != 0 {
  46. panic("dm/security: input not full blocks")
  47. }
  48. if len(dst) < len(src) {
  49. panic("dm/security: output smaller than input")
  50. }
  51. if InexactOverlap(dst[:len(src)], src) {
  52. panic("dm/security: invalid buffer overlap")
  53. }
  54. for bs, be := 0, x.blockSize; bs < len(src); bs, be = bs+x.blockSize, be+x.blockSize {
  55. x.b.Decrypt(dst[bs:be], src[bs:be])
  56. }
  57. }