From c537f79ccce9315d9438a2b1e182186941b57070 Mon Sep 17 00:00:00 2001 From: eater <=@eater.me> Date: Sun, 11 Aug 2019 15:14:20 +0200 Subject: [PATCH] Add padding processing --- crypto.go | 49 ++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 48 insertions(+), 1 deletion(-) diff --git a/crypto.go b/crypto.go index 0b08bcc..0b24f7a 100644 --- a/crypto.go +++ b/crypto.go @@ -43,7 +43,7 @@ func DecryptAndVerify(input []byte, key *rsa.PrivateKey, pub *rsa.PublicKey, sig body := make([]byte, len(encBody)) dec := cipher2.NewCBCDecrypter(cipher, iv) dec.CryptBlocks(body, encBody) - err = json.Unmarshal(body, v) + err = json.Unmarshal(unpad(body), v) if err != nil { return err @@ -111,7 +111,54 @@ func EncryptAndSign(v interface{}, key *rsa.PrivateKey, pub *rsa.PublicKey, sign encBody := make([]byte, len(body)) enc := cipher2.NewCBCEncrypter(cipher, iv) enc.CryptBlocks(encBody, body) + + copy(pad(encBody), encBody[len(encBody):]) writer.Write([]byte(hex.EncodeToString(encBody))) return nil } + +func pad(body []byte) []byte { + rest := len(body) % 8 + if rest == 0 { + padLen := getPad(body) + if padLen != 0 { + return []byte{8, 8, 8, 8, 8, 8, 8, 8} + } + + return []byte{} + } + + pad := make([]byte, rest) + + for i := 0; i < rest; i++ { + pad[i] = byte(rest) + } + + return pad +} + +func getPad(body []byte) int { + lastIndex := len(body) - 1 + padLen := body[lastIndex] + if 1 < padLen && padLen < 9 { + isPadding := true + + for i := byte(0); i < padLen; i++ { + if body[-i] != padLen { + isPadding = false + break + } + } + + if isPadding { + return int(padLen) + } + } + + return 0 +} + +func unpad(body []byte) []byte { + return body[:len(body)-getPad(body)] +}