diff --git a/crypto.go b/crypto.go index 0b24f7a..1a2c590 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(unpad(body), v) + err = json.Unmarshal(Unpad(body), v) if err != nil { return err @@ -112,16 +112,16 @@ func EncryptAndSign(v interface{}, key *rsa.PrivateKey, pub *rsa.PublicKey, sign enc := cipher2.NewCBCEncrypter(cipher, iv) enc.CryptBlocks(encBody, body) - copy(pad(encBody), encBody[len(encBody):]) + copy(encBody[len(encBody):], Pad(encBody)) writer.Write([]byte(hex.EncodeToString(encBody))) return nil } -func pad(body []byte) []byte { +func Pad(body []byte) []byte { rest := len(body) % 8 if rest == 0 { - padLen := getPad(body) + padLen := GetPad(body) if padLen != 0 { return []byte{8, 8, 8, 8, 8, 8, 8, 8} } @@ -129,36 +129,37 @@ func pad(body []byte) []byte { return []byte{} } - pad := make([]byte, rest) + padLen := 8 - rest + pad := make([]byte, padLen) - for i := 0; i < rest; i++ { - pad[i] = byte(rest) + for i := 0; i < padLen; i++ { + pad[i] = byte(padLen) } return pad } -func getPad(body []byte) int { +func GetPad(body []byte) int { lastIndex := len(body) - 1 - padLen := body[lastIndex] + padLen := int(body[lastIndex]) if 1 < padLen && padLen < 9 { isPadding := true - for i := byte(0); i < padLen; i++ { - if body[-i] != padLen { + for i := 0; i < padLen; i++ { + if body[lastIndex-i] != byte(padLen) { isPadding = false break } } if isPadding { - return int(padLen) + return padLen } } return 0 } -func unpad(body []byte) []byte { - return body[:len(body)-getPad(body)] +func Unpad(body []byte) []byte { + return body[:len(body)-GetPad(body)] } diff --git a/crypto_test.go b/crypto_test.go index 4c6c604..71032cf 100644 --- a/crypto_test.go +++ b/crypto_test.go @@ -8,6 +8,22 @@ import ( "testing" ) +func TestPadding(t *testing.T) { + x := []byte{0, 0, 0} + x = append(x, service.Pad(x)...) + + padLen := service.GetPad(x) + + if padLen != 5 { + t.Errorf("Failed adding/measuring padding, Pad(%v, len=%d)", x, padLen) + } + + y := service.Unpad(x) + if len(y) != 3 { + t.Errorf("Failed padding and unpadding, Pad(%v), Unpad(%v)", x, y) + } +} + func TestSingleRound(t *testing.T) { keyA, _ := rsa.GenerateKey(rand.Reader, 4096) keyB, _ := rsa.GenerateKey(rand.Reader, 4096)