@@ -336,6 +336,7 @@ static void free_crypt_cipher_context(CRYPT_CTX *ctx);
336
336
if (ctx -> cipher_ctx == NULL )
337
337
ctx -> cipher_ctx = malloc (sizeof (mbedtls_gcm_context ));
338
338
mbedtls_gcm_init ((mbedtls_gcm_context * )ctx -> cipher_ctx );
339
+ ctx -> cipher_mode = MBEDTLS_MODE_GCM ;
339
340
switch (type ) {
340
341
case SYM_AES_128_GCM :
341
342
case SYM_ARIA_128_GCM :
@@ -494,8 +495,6 @@ static void free_crypt_cipher_context(CRYPT_CTX *ctx);
494
495
495
496
* olen = 0 ;
496
497
497
- if (len == 0 ) return 0 ;
498
-
499
498
bin = ctx -> buffer ;
500
499
blk = ctx -> cipher_block_size ;
501
500
@@ -610,6 +609,14 @@ static void free_crypt_cipher_context(CRYPT_CTX *ctx);
610
609
#endif
611
610
{
612
611
size_t out_bytes = 0 ;
612
+
613
+ if (ctx -> state == CRYPT_PORT_NO_DATA && ctx -> aad_len ) {
614
+ if (len < ctx -> aad_len ) return 1 ;
615
+ err = mbedtls_gcm_update_ad ((mbedtls_gcm_context * )ctx -> cipher_ctx , input , ctx -> aad_len );
616
+ if (err ) return err ;
617
+ input += ctx -> aad_len ;
618
+ len -= ctx -> aad_len ;
619
+ }
613
620
err = mbedtls_gcm_update ((mbedtls_gcm_context * )ctx -> cipher_ctx , input , len , BIN_TAIL (bin ), len , & out_bytes );
614
621
if (err ) return err ;
615
622
SERIES_TAIL (bin ) += out_bytes ;
@@ -876,7 +883,7 @@ static void free_crypt_cipher_context(CRYPT_CTX *ctx);
876
883
REBSER * bin ;
877
884
REBCNT len , ofs , blk ;
878
885
REBINT ret = CRYPT_OK ;
879
- REBCNT olen = 0 ;
886
+ size_t olen = 0 ;
880
887
881
888
bin = ctx -> buffer ;
882
889
@@ -910,6 +917,19 @@ static void free_crypt_cipher_context(CRYPT_CTX *ctx);
910
917
ret = Crypt_Crypt (ctx , ctx -> unprocessed_data , blk , & olen );
911
918
ctx -> unprocessed_len = 0 ;
912
919
}
920
+ if (ctx -> tag_len ) {
921
+ #ifdef MBEDTLS_GCM_C
922
+ if (ctx -> cipher_mode == MBEDTLS_MODE_GCM ) {
923
+ // compute tag
924
+ Extend_Series (bin , ctx -> tag_len );
925
+ ret = mbedtls_gcm_finish ((mbedtls_gcm_context * )ctx -> cipher_ctx , NULL , 0 , & olen , BIN_TAIL (bin ), ctx -> tag_len );
926
+ if (ret ) return ret ;
927
+ SERIES_TAIL (bin ) += ctx -> tag_len ;
928
+ ctx -> state = CRYPT_PORT_FINISHED ;
929
+ }
930
+ #endif
931
+ }
932
+
913
933
return ret ;
914
934
}
915
935
@@ -923,13 +943,19 @@ static void free_crypt_cipher_context(CRYPT_CTX *ctx);
923
943
REBCNT blk , olen ;
924
944
REBCNT unprocessed_free ;
925
945
926
- if (len == 0 ) return 0 ;
927
-
928
946
if (ctx -> state == CRYPT_PORT_NEEDS_INIT ) {
929
947
ret = Crypt_Init (ctx );
930
948
if (ret ) return ret ;
931
949
}
932
950
951
+ if (len == 0 ) {
952
+ // it is valid to encrypt empty message
953
+ if (ctx -> cipher_mode == MBEDTLS_MODE_GCM ) {
954
+ ret = Crypt_Crypt (ctx , input , 0 , & olen );
955
+ }
956
+ return ret ;
957
+ }
958
+
933
959
blk = ctx -> cipher_block_size ;
934
960
if (blk > MBEDTLS_MAX_BLOCK_LENGTH ) return CRYPT_ERROR_BAD_BLOCK_SIZE ;
935
961
0 commit comments