From: Adam Langley Date: Fri, 21 Sep 2012 19:54:03 +0000 (+1000) Subject: [release-branch.go1] crypto/rsa: left-pad PKCS#1 v1.5 outputs. X-Git-Tag: go1.0.3~161 X-Git-Url: http://www.git.cypherpunks.su/?a=commitdiff_plain;h=9dec2eb42a3a059183621884d4bcf8340e39ff95;p=gostls13.git [release-branch.go1] crypto/rsa: left-pad PKCS#1 v1.5 outputs. ««« backport 46ca86e70e96 crypto/rsa: left-pad PKCS#1 v1.5 outputs. OpenSSL requires that RSA signatures be exactly the same byte-length as the modulus. Currently it'll reject ~1/256 of our signatures: those that end up a byte shorter. Fixes #3796. R=golang-dev, edsrzf, r CC=golang-dev https://golang.org/cl/6352093 »»» --- diff --git a/src/pkg/crypto/rsa/pkcs1v15.go b/src/pkg/crypto/rsa/pkcs1v15.go index a32236e472..f39a48a6af 100644 --- a/src/pkg/crypto/rsa/pkcs1v15.go +++ b/src/pkg/crypto/rsa/pkcs1v15.go @@ -25,10 +25,10 @@ func EncryptPKCS1v15(rand io.Reader, pub *PublicKey, msg []byte) (out []byte, er return } - // EM = 0x02 || PS || 0x00 || M - em := make([]byte, k-1) - em[0] = 2 - ps, mm := em[1:len(em)-len(msg)-1], em[len(em)-len(msg):] + // EM = 0x00 || 0x02 || PS || 0x00 || M + em := make([]byte, k) + em[1] = 2 + ps, mm := em[2:len(em)-len(msg)-1], em[len(em)-len(msg):] err = nonZeroRandomBytes(ps, rand) if err != nil { return @@ -38,7 +38,9 @@ func EncryptPKCS1v15(rand io.Reader, pub *PublicKey, msg []byte) (out []byte, er m := new(big.Int).SetBytes(em) c := encrypt(new(big.Int), pub, m) - out = c.Bytes() + + copyWithLeftPad(em, c.Bytes()) + out = em return } @@ -185,9 +187,12 @@ func SignPKCS1v15(rand io.Reader, priv *PrivateKey, hash crypto.Hash, hashed []b m := new(big.Int).SetBytes(em) c, err := decrypt(rand, priv, m) - if err == nil { - s = c.Bytes() + if err != nil { + return } + + copyWithLeftPad(em, c.Bytes()) + s = em return } @@ -241,3 +246,13 @@ func pkcs1v15HashInfo(hash crypto.Hash, inLen int) (hashLen int, prefix []byte, } return } + +// copyWithLeftPad copies src to the end of dest, padding with zero bytes as +// needed. +func copyWithLeftPad(dest, src []byte) { + numPaddingBytes := len(dest) - len(src) + for i := 0; i < numPaddingBytes; i++ { + dest[i] = 0 + } + copy(dest[numPaddingBytes:], src) +}