Make ctr mode behaviour consistent with other modes.
[openssl.git] / crypto / evp / evp_enc.c
index 6e582c458de55b5fc7b230d3d3c546fc42cbbb43..a35621a2ec9d27fc3db44baf9bb499b8711b0e5e 100644 (file)
@@ -206,11 +206,14 @@ skip_to_init:
                        ctx->num = 0;
 
                        case EVP_CIPH_CBC_MODE:
+                       case EVP_CIPH_CTR_MODE:
 
                        OPENSSL_assert(EVP_CIPHER_CTX_iv_length(ctx) <=
                                        (int)sizeof(ctx->iv));
                        if(iv) memcpy(ctx->oiv, iv, EVP_CIPHER_CTX_iv_length(ctx));
-                       memcpy(ctx->iv, ctx->oiv, EVP_CIPHER_CTX_iv_length(ctx));
+                       /* Don't reuse IV for CTR mode */
+                       if (EVP_CIPHER_CTX_mode(ctx) != EVP_CIPH_CTR_MODE)
+                               memcpy(ctx->iv, ctx->oiv, EVP_CIPHER_CTX_iv_length(ctx));
                        break;
 
                        default:
@@ -566,3 +569,38 @@ int EVP_CIPHER_CTX_rand_key(EVP_CIPHER_CTX *ctx, unsigned char *key)
        return 1;
        }
 
+int EVP_CIPHER_CTX_copy(EVP_CIPHER_CTX *out, const EVP_CIPHER_CTX *in)
+       {
+       if ((in == NULL) || (in->cipher == NULL))
+               {
+               EVPerr(EVP_F_EVP_CIPHER_CTX_COPY,EVP_R_INPUT_NOT_INITIALIZED);
+               return 0;
+               }
+#ifndef OPENSSL_NO_ENGINE
+       /* Make sure it's safe to copy a cipher context using an ENGINE */
+       if (in->engine && !ENGINE_init(in->engine))
+               {
+               EVPerr(EVP_F_EVP_CIPHER_CTX_COPY,ERR_R_ENGINE_LIB);
+               return 0;
+               }
+#endif
+
+       EVP_CIPHER_CTX_cleanup(out);
+       memcpy(out,in,sizeof *out);
+
+       if (in->cipher_data && in->cipher->ctx_size)
+               {
+               out->cipher_data=OPENSSL_malloc(in->cipher->ctx_size);
+               if (!out->cipher_data)
+                       {
+                       EVPerr(EVP_F_EVP_CIPHER_CTX_COPY,ERR_R_MALLOC_FAILURE);
+                       return 0;
+                       }
+               memcpy(out->cipher_data,in->cipher_data,in->cipher->ctx_size);
+               }
+
+       if (in->cipher->flags & EVP_CIPH_CUSTOM_COPY)
+               return in->cipher->ctrl((EVP_CIPHER_CTX *)in, EVP_CTRL_COPY, 0, out);
+       return 1;
+       }
+