Add padding processing

master
eater 5 years ago
parent 4eecf0b3e5
commit c537f79ccc
Signed by: eater
GPG Key ID: 656785D50BE51C0A

@ -43,7 +43,7 @@ func DecryptAndVerify(input []byte, key *rsa.PrivateKey, pub *rsa.PublicKey, sig
body := make([]byte, len(encBody)) body := make([]byte, len(encBody))
dec := cipher2.NewCBCDecrypter(cipher, iv) dec := cipher2.NewCBCDecrypter(cipher, iv)
dec.CryptBlocks(body, encBody) dec.CryptBlocks(body, encBody)
err = json.Unmarshal(body, v) err = json.Unmarshal(unpad(body), v)
if err != nil { if err != nil {
return err return err
@ -111,7 +111,54 @@ func EncryptAndSign(v interface{}, key *rsa.PrivateKey, pub *rsa.PublicKey, sign
encBody := make([]byte, len(body)) encBody := make([]byte, len(body))
enc := cipher2.NewCBCEncrypter(cipher, iv) enc := cipher2.NewCBCEncrypter(cipher, iv)
enc.CryptBlocks(encBody, body) enc.CryptBlocks(encBody, body)
copy(pad(encBody), encBody[len(encBody):])
writer.Write([]byte(hex.EncodeToString(encBody))) writer.Write([]byte(hex.EncodeToString(encBody)))
return nil 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)]
}

Loading…
Cancel
Save