pkcs5.go 737 B

123456789101112131415161718192021222324252627282930
  1. package padding
  2. var (
  3. PKCS5 = &pkcs5{}
  4. )
  5. // pkcs5Padding is a pkcs5 padding struct.
  6. type pkcs5 struct{}
  7. // Padding implements the Padding interface Padding method.
  8. func (p *pkcs5) Padding(src []byte, blockSize int) []byte {
  9. srcLen := len(src)
  10. padLen := byte(blockSize - (srcLen % blockSize))
  11. pd := make([]byte, srcLen+int(padLen))
  12. copy(pd, src)
  13. for i := srcLen; i < len(pd); i++ {
  14. pd[i] = padLen
  15. }
  16. return pd
  17. }
  18. // Unpadding implements the Padding interface Unpadding method.
  19. func (p *pkcs5) Unpadding(src []byte, blockSize int) ([]byte, error) {
  20. srcLen := len(src)
  21. paddingLen := int(src[srcLen-1])
  22. if paddingLen >= srcLen || paddingLen > blockSize {
  23. return nil, ErrPaddingSize
  24. }
  25. return src[:srcLen-paddingLen], nil
  26. }