@@ -514,5 +514,75 @@ int test_aes256_ctr_stream(ENGINE *e, void *data)
514514 return err ;
515515}
516516
517+ /* OpenSSL allows the user to call EVP_CipherInit with NULL key or IV. In the
518+ * past, setting the IV first (with key NULL) with wolfEngine and then setting
519+ * the key (with IV NULL) would result in the IV getting set to 0s on the call
520+ * to set the key. This was discovered in testing with OpenSSH. This is a
521+ * regression test to ensure we preserve the IV in this scenario. */
522+ int test_aes_ctr_iv_init_regression (ENGINE * e , void * data )
523+ {
524+ int err = 0 ;
525+ unsigned char iv [AES_BLOCK_SIZE ];
526+ unsigned char key [16 ];
527+ EVP_CIPHER_CTX * encCtx = NULL ;
528+ EVP_CIPHER_CTX * decCtx = NULL ;
529+ const unsigned char plainText [] = "Lorem ipsum dolor sit amet" ;
530+ unsigned char encText [sizeof (plainText )];
531+ unsigned char decText [sizeof (plainText )];
532+
533+ (void )data ;
534+
535+ /* Generate a random IV and key. */
536+ err = RAND_bytes (iv , AES_BLOCK_SIZE ) != 1 ;
537+ if (err == 0 ) {
538+ err = RAND_bytes (key , 16 ) != 1 ;
539+ }
540+
541+ /* Create encryption context. Use OpenSSL for encryption. */
542+ if (err == 0 ) {
543+ err = (encCtx = EVP_CIPHER_CTX_new ()) == NULL ;
544+ }
545+ if (err == 0 ) {
546+ err = EVP_CipherInit_ex (encCtx , EVP_aes_128_ctr (), NULL , NULL , iv , 1 )
547+ != 1 ;
548+ }
549+ if (err == 0 ) {
550+ err = EVP_CipherInit_ex (encCtx , NULL , NULL , key , NULL , -1 ) != 1 ;
551+ }
552+
553+ /* Create decryption context. Use wolfEngine for decryption. */
554+ if (err == 0 ) {
555+ err = (decCtx = EVP_CIPHER_CTX_new ()) == NULL ;
556+ }
557+ if (err == 0 ) {
558+ err = EVP_CipherInit_ex (decCtx , EVP_aes_128_ctr (), e , NULL , iv , 0 ) != 1 ;
559+ }
560+ if (err == 0 ) {
561+ err = EVP_CipherInit_ex (decCtx , NULL , e , key , NULL , -1 ) != 1 ;
562+ }
563+
564+ /* Encrypt. */
565+ if (err == 0 ) {
566+ err = EVP_Cipher (encCtx , encText , plainText , sizeof (plainText )) < 0 ;
567+ }
568+
569+ /* Decrypt. */
570+ if (err == 0 ) {
571+ err = EVP_Cipher (decCtx , decText , encText , sizeof (plainText )) < 0 ;
572+ }
573+
574+ /* Ensure decrypted and plaintext match. */
575+ if (err == 0 ) {
576+ err = memcmp (decText , plainText , sizeof (plainText )) != 0 ;
577+ }
578+
579+ if (encCtx != NULL )
580+ EVP_CIPHER_CTX_free (encCtx );
581+ if (decCtx != NULL )
582+ EVP_CIPHER_CTX_free (decCtx );
583+
584+ return err ;
585+ }
586+
517587#endif /* WE_HAVE_AESCTR */
518588
0 commit comments