Fix unintended sign extension
[openssl.git] / crypto / modes / wrap128.c
index 2f65314cfa26c181e9ae21a1136d441b35cffc54..73718ae59feb1871742b8374d5c3c966e015804a 100644 (file)
@@ -230,8 +230,13 @@ size_t CRYPTO_128_wrap_pad(void *key, const unsigned char *icv,
                            const unsigned char *in, size_t inlen,
                            block128_f block)
 {
-    /* n: number of 64-bit blocks in the padded key data */
-    const size_t blocks_padded = (inlen + 8) / 8;
+    /* n: number of 64-bit blocks in the padded key data
+     *
+     * If length of plain text is not a multiple of 8, pad the plain text octet
+     * string on the right with octets of zeros, where final length is the
+     * smallest multiple of 8 that is greater than length of plain text.
+     * If length of plain text is a multiple of 8, then there is no padding. */
+    const size_t blocks_padded = (inlen + 7) / 8; /* CEILING(m/8) */
     const size_t padded_len = blocks_padded * 8;
     const size_t padding_len = padded_len - inlen;
     /* RFC 5649 section 3: Alternative Initial Value */
@@ -345,7 +350,10 @@ size_t CRYPTO_128_unwrap_pad(void *key, const unsigned char *icv,
      * LSB(32,AIV).
      */
 
-    ptext_len = (aiv[4] << 24) | (aiv[5] << 16) | (aiv[6] << 8) | aiv[7];
+    ptext_len =   ((unsigned int)aiv[4] << 24)
+                | ((unsigned int)aiv[5] << 16)
+                | ((unsigned int)aiv[6] <<  8)
+                |  (unsigned int)aiv[7];
     if (8 * (n - 1) >= ptext_len || ptext_len > 8 * n) {
         OPENSSL_cleanse(out, inlen);
         return 0;