Actually make Padding work

master
eater 5 years ago
parent c537f79ccc
commit a683caaf76
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))
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)]
}

@ -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)

Loading…
Cancel
Save