aboutsummaryrefslogblamecommitdiffstats
path: root/lib/crypto/c_src/pkey.c
blob: 4cad9b6003f8f69a2b83b5472cb0d22d93a72917 (plain) (tree)
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356



















                                                                           

















































                                                                                                           

                                                   
                 

                                
      



                                               









                                                                            
               


                                  



                             

                         






                                                                         
                                                            












                                                              



                                                         


                                                      



                                                                                      


                                                      

                                                                           



                                                  
                                                                               







                                                                     





                      










                                  








                                                                                              
 

                                    







                                             
                                         
                       
 























                                                                                  
                                 


                                                         
     
                                   
      



















                                                                          


                   


                       



                                                                                                          








                            



                                      

                                                      

                     
                                              

                                                                


                           












                                                  

                                         


                                      

















                                                                              




                                         

                                                 
     
                           

                                       



                                                
 





                                                  
 



                           


























                              




                                                                                        








                            



                                      

                                                      

                     
                                              

                                                               



                                        












                                                  

                                         


                                      


















                                                                              




                                         


                                                 
     
                           

                                       












                                                  



                           


























                              




                                                                               

                          

                                            



                             
                       
                             

                  

                        




                                               




                      






                                                                           
                                  
                           


                                                                                           






                     


                                                                   






                     

     

                                                                      

                       

                                                     

                                





                                                            


                              

                                                                        



                                                           

                                                                                
      
                            

             




                                                                                        




                                

                                               
 






                                                                   
 

                                                                           
     
                     
      





                                                                



                                                                  

                                                                        
     



                              













                                                                                        
                                     













                                                                          

                                       












                                                                           
     
                    

            
                     


      




                                                              
     










                                          
 















                                      
                       

                               
      



                            




                                                                                 
               

                                            
                          
                       
                             





                                               








                             

                          
                                  
                           

      
                                                     
                                     

                                                                                           






                     


                                                                   






                     


                                                                       
                     




                               

                                                     

                                





                                                            


                              


                                                                        

                                              

                                                                                
      
                            

             




                                                                                        

     
                                
                 

                                               
        

                                                                     
 
                                                                                  
     
                     
      


                                                                  
         

                                                                               


                              



                               
                              


                                                                                                                
                                     


                                                                                       

                                       


                                                                                                      
     
                    

            
                     


      

                                                 
 








                                
                       





                               
      











                            
























































































































































































































































































































































































































































































                                                                                                                              
/*
 * %CopyrightBegin%
 *
 * Copyright Ericsson AB 2010-2018. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * %CopyrightEnd%
 */

#include "pkey.h"
#include "bn.h"
#include "digest.h"
#include "dss.h"
#include "ec.h"
#include "eddsa.h"
#include "engine.h"
#include "rsa.h"

#define PKEY_BADARG -1
#define PKEY_NOTSUP 0
#define PKEY_OK 1

typedef struct PKeyCryptOptions {
    const EVP_MD *rsa_mgf1_md;
    ErlNifBinary rsa_oaep_label;
    const EVP_MD *rsa_oaep_md;
    int rsa_padding;
    const EVP_MD *signature_md;
} PKeyCryptOptions;

typedef struct PKeySignOptions {
    const EVP_MD *rsa_mgf1_md;
    int rsa_padding;
    int rsa_pss_saltlen;
} PKeySignOptions;


static int get_pkey_digest_type(ErlNifEnv *env, ERL_NIF_TERM algorithm, ERL_NIF_TERM type,
				const EVP_MD **md);
static int get_pkey_sign_digest(ErlNifEnv *env, ERL_NIF_TERM algorithm,
				ERL_NIF_TERM type, ERL_NIF_TERM data,
				unsigned char *md_value, const EVP_MD **mdp,
				unsigned char **tbsp, size_t *tbslenp);
static int get_pkey_sign_options(ErlNifEnv *env, ERL_NIF_TERM algorithm, ERL_NIF_TERM options,
                                 const EVP_MD *md, PKeySignOptions *opt);
static int get_pkey_private_key(ErlNifEnv *env, ERL_NIF_TERM algorithm, ERL_NIF_TERM key, EVP_PKEY **pkey);
static int get_pkey_public_key(ErlNifEnv *env, ERL_NIF_TERM algorithm, ERL_NIF_TERM key,
			       EVP_PKEY **pkey);
static int get_pkey_crypt_options(ErlNifEnv *env, ERL_NIF_TERM algorithm, ERL_NIF_TERM options,
				  PKeyCryptOptions *opt);
static size_t size_of_RSA(EVP_PKEY *pkey);


static int get_pkey_digest_type(ErlNifEnv *env, ERL_NIF_TERM algorithm, ERL_NIF_TERM type,
				const EVP_MD **md)
{
    struct digest_type_t *digp = NULL;
    *md = NULL;

    if (type == atom_none && algorithm == atom_rsa)
        return PKEY_OK;
#ifdef HAVE_EDDSA
    if (algorithm == atom_eddsa)
        return PKEY_OK;
#endif
    if ((digp = get_digest_type(type)) == NULL)
        return PKEY_BADARG;
    if (digp->md.p == NULL)
        return PKEY_NOTSUP;

    *md = digp->md.p;
    return PKEY_OK;
}

static int get_pkey_sign_digest(ErlNifEnv *env, ERL_NIF_TERM algorithm,
				ERL_NIF_TERM type, ERL_NIF_TERM data,
				unsigned char *md_value, const EVP_MD **mdp,
				unsigned char **tbsp, size_t *tbslenp)
{
    int i, ret;
    const ERL_NIF_TERM *tpl_terms;
    int tpl_arity;
    ErlNifBinary tbs_bin;
    EVP_MD_CTX *mdctx = NULL;
    const EVP_MD *md;
    unsigned char *tbs;
    size_t tbslen;
    unsigned int tbsleni;

    md = *mdp;
    tbs = *tbsp;
    tbslen = *tbslenp;

    if ((i = get_pkey_digest_type(env, algorithm, type, &md)) != PKEY_OK)
        return i;

    if (enif_get_tuple(env, data, &tpl_arity, &tpl_terms)) {
        if (tpl_arity != 2)
            goto bad_arg;
        if (tpl_terms[0] != atom_digest)
            goto bad_arg;
        if (!enif_inspect_binary(env, tpl_terms[1], &tbs_bin))
            goto bad_arg;
        if (tbs_bin.size > INT_MAX)
            goto bad_arg;
        if (md != NULL) {
            if ((int)tbs_bin.size != EVP_MD_size(md))
                goto bad_arg;
        }

        /* We have a digest (= hashed text) in tbs_bin */
	tbs = tbs_bin.data;
	tbslen = tbs_bin.size;
    } else if (md == NULL) {
        if (!enif_inspect_binary(env, data, &tbs_bin))
            goto bad_arg;

        /* md == NULL, that is no hashing because DigestType argument was atom_none */
	tbs = tbs_bin.data;
	tbslen = tbs_bin.size;
    } else {
        if (!enif_inspect_binary(env, data, &tbs_bin))
            goto bad_arg;

        /* We have the cleartext in tbs_bin and the hash algo info in md */
	tbs = md_value;

        if ((mdctx = EVP_MD_CTX_create()) == NULL)
            goto err;

        /* Looks well, now hash the plain text into a digest according to md */
        if (EVP_DigestInit_ex(mdctx, md, NULL) != 1)
            goto err;
        if (EVP_DigestUpdate(mdctx, tbs_bin.data, tbs_bin.size) != 1)
            goto err;
        if (EVP_DigestFinal_ex(mdctx, tbs, &tbsleni) != 1)
            goto err;

        tbslen = (size_t)tbsleni;
    }

    *mdp = md;
    *tbsp = tbs;
    *tbslenp = tbslen;

    ret = PKEY_OK;
    goto done;

 bad_arg:
 err:
    ret = PKEY_BADARG;

 done:
    if (mdctx)
        EVP_MD_CTX_destroy(mdctx);
    return ret;
}

static int get_pkey_sign_options(ErlNifEnv *env, ERL_NIF_TERM algorithm, ERL_NIF_TERM options,
                                 const EVP_MD *md, PKeySignOptions *opt)
{
    ERL_NIF_TERM head, tail;
    const ERL_NIF_TERM *tpl_terms;
    int tpl_arity;
    const EVP_MD *opt_md;

    if (!enif_is_list(env, options))
        goto bad_arg;

    /* defaults */
    if (algorithm == atom_rsa) {
	opt->rsa_mgf1_md = NULL;
	opt->rsa_padding = RSA_PKCS1_PADDING;
	opt->rsa_pss_saltlen = -2;
    }

    if (enif_is_empty_list(env, options))
	return PKEY_OK;

    if (algorithm != atom_rsa)
        goto bad_arg;

    tail = options;
    while (enif_get_list_cell(env, tail, &head, &tail)) {
        if (!enif_get_tuple(env, head, &tpl_arity, &tpl_terms))
            goto bad_arg;
        if (tpl_arity != 2)
            goto bad_arg;

        if (tpl_terms[0] == atom_rsa_mgf1_md && enif_is_atom(env, tpl_terms[1])) {
            int result;

            result = get_pkey_digest_type(env, algorithm, tpl_terms[1], &opt_md);
            if (result != PKEY_OK)
                return result;

            opt->rsa_mgf1_md = opt_md;

        } else if (tpl_terms[0] == atom_rsa_padding) {
            if (tpl_terms[1] == atom_rsa_pkcs1_padding) {
                opt->rsa_padding = RSA_PKCS1_PADDING;

            } else if (tpl_terms[1] == atom_rsa_pkcs1_pss_padding) {
#ifdef HAVE_RSA_PKCS1_PSS_PADDING
                opt->rsa_padding = RSA_PKCS1_PSS_PADDING;
                if (opt->rsa_mgf1_md == NULL)
                    opt->rsa_mgf1_md = md;
#else
                return PKEY_NOTSUP;
#endif

            } else if (tpl_terms[1] == atom_rsa_x931_padding) {
                opt->rsa_padding = RSA_X931_PADDING;

            } else if (tpl_terms[1] == atom_rsa_no_padding) {
                opt->rsa_padding = RSA_NO_PADDING;

            } else {
                goto bad_arg;
            }

        } else if (tpl_terms[0] == atom_rsa_pss_saltlen) {
            if (!enif_get_int(env, tpl_terms[1], &(opt->rsa_pss_saltlen)))
                goto bad_arg;
            if (opt->rsa_pss_saltlen < -2)
                goto bad_arg;

        } else {
            goto bad_arg;
        }
    }

    return PKEY_OK;

 bad_arg:
    return PKEY_BADARG;
}

static int get_pkey_private_key(ErlNifEnv *env, ERL_NIF_TERM algorithm, ERL_NIF_TERM key, EVP_PKEY **pkey)
{
    EVP_PKEY *result = NULL;
    RSA *rsa = NULL;
    DSA *dsa = NULL;
#if defined(HAVE_EC)
    EC_KEY *ec = NULL;
#endif
    char *id = NULL;
    char *password = NULL;

    if (enif_is_map(env, key)) {
#ifdef HAS_ENGINE_SUPPORT
        /* Use key stored in engine */
        ENGINE *e;

        if (!get_engine_and_key_id(env, key, &id, &e))
            goto err;

        password = get_key_password(env, key);
        result = ENGINE_load_private_key(e, id, NULL, password);

#else
        return PKEY_BADARG;
#endif
    } else if (algorithm == atom_rsa) {
        if ((rsa = RSA_new()) == NULL)
            goto err;

        if (!get_rsa_private_key(env, key, rsa))
            goto err;
        if ((result = EVP_PKEY_new()) == NULL)
            goto err;
        if (EVP_PKEY_assign_RSA(result, rsa) != 1)
            goto err;
        /* On success, result owns rsa */
        rsa = NULL;

    } else if (algorithm == atom_ecdsa) {
#if defined(HAVE_EC)
	const ERL_NIF_TERM *tpl_terms;
	int tpl_arity;

        if (!enif_get_tuple(env, key, &tpl_arity, &tpl_terms))
            goto err;
        if (tpl_arity != 2)
            goto err;
        if (!enif_is_tuple(env, tpl_terms[0]))
            goto err;
        if (!enif_is_binary(env, tpl_terms[1]))
            goto err;
        if (!get_ec_key(env, tpl_terms[0], tpl_terms[1], atom_undefined, &ec))
            goto err;

        if ((result = EVP_PKEY_new()) == NULL)
            goto err;
        if (EVP_PKEY_assign_EC_KEY(result, ec) != 1)
            goto err;
        /* On success, result owns ec */
        ec = NULL;

#else
	return PKEY_NOTSUP;
#endif
    } else if (algorithm == atom_eddsa) {
#if defined(HAVE_EDDSA)
        if (!get_eddsa_key(env, 0, key, &result))
            goto err;
#else
	return PKEY_NOTSUP;
#endif
    } else if (algorithm == atom_dss) {
        if ((dsa = DSA_new()) == NULL)
            goto err;
        if (!get_dss_private_key(env, key, dsa))
            goto err;

        if ((result = EVP_PKEY_new()) == NULL)
            goto err;
        if (EVP_PKEY_assign_DSA(result, dsa) != 1)
            goto err;
        /* On success, result owns dsa */
        dsa = NULL;

    } else {
	return PKEY_BADARG;
    }

    goto done;

 err:
    if (result)
        EVP_PKEY_free(result);
    result = NULL;

 done:
    if (password)
        enif_free(password);
    if (id)
        enif_free(id);
    if (rsa)
        RSA_free(rsa);
    if (dsa)
        DSA_free(dsa);
#ifdef HAVE_EC
    if (ec)
        EC_KEY_free(ec);
#endif

    if (result == NULL) {
        return PKEY_BADARG;
    } else {
        *pkey = result;
        return PKEY_OK;
    }
}

static int get_pkey_public_key(ErlNifEnv *env, ERL_NIF_TERM algorithm, ERL_NIF_TERM key,
			       EVP_PKEY **pkey)
{
    EVP_PKEY *result = NULL;
    RSA *rsa = NULL;
    DSA *dsa = NULL;
#if defined(HAVE_EC)
    EC_KEY *ec = NULL;
#endif
    char *id = NULL;
    char *password = NULL;

    if (enif_is_map(env, key)) {
#ifdef HAS_ENGINE_SUPPORT
        /* Use key stored in engine */
        ENGINE *e;

        if (!get_engine_and_key_id(env, key, &id, &e))
            goto err;

        password = get_key_password(env, key);
        result = ENGINE_load_public_key(e, id, NULL, password);

#else
        return PKEY_BADARG;
#endif
    } else  if (algorithm == atom_rsa) {
        if ((rsa = RSA_new()) == NULL)
            goto err;

        if (!get_rsa_public_key(env, key, rsa))
            goto err;

        if ((result = EVP_PKEY_new()) == NULL)
            goto err;
        if (EVP_PKEY_assign_RSA(result, rsa) != 1)
            goto err;
        /* On success, result owns rsa */
        rsa = NULL;

    } else if (algorithm == atom_ecdsa) {
#if defined(HAVE_EC)
	const ERL_NIF_TERM *tpl_terms;
	int tpl_arity;

        if (!enif_get_tuple(env, key, &tpl_arity, &tpl_terms))
            goto err;
        if (tpl_arity != 2)
            goto err;
        if (!enif_is_tuple(env, tpl_terms[0]))
            goto err;
        if (!enif_is_binary(env, tpl_terms[1]))
            goto err;
        if (!get_ec_key(env, tpl_terms[0], atom_undefined, tpl_terms[1], &ec))
            goto err;

        if ((result = EVP_PKEY_new()) == NULL)
            goto err;

        if (EVP_PKEY_assign_EC_KEY(result, ec) != 1)
            goto err;
        /* On success, result owns ec */
        ec = NULL;

#else
	return PKEY_NOTSUP;
#endif
    } else if (algorithm == atom_eddsa) {
#if defined(HAVE_EDDSA)
        if (!get_eddsa_key(env, 1, key, &result))
            goto err;

#else
	return PKEY_NOTSUP;
#endif
    } else if (algorithm == atom_dss) {
        if ((dsa = DSA_new()) == NULL)
            goto err;

        if (!get_dss_public_key(env, key, dsa))
            goto err;

        if ((result = EVP_PKEY_new()) == NULL)
            goto err;
        if (EVP_PKEY_assign_DSA(result, dsa) != 1)
            goto err;
        /* On success, result owns dsa */
        dsa = NULL;

    } else {
	return PKEY_BADARG;
    }

    goto done;

 err:
    if (result)
        EVP_PKEY_free(result);
    result = NULL;

 done:
    if (password)
        enif_free(password);
    if (id)
        enif_free(id);
    if (rsa)
        RSA_free(rsa);
    if (dsa)
        DSA_free(dsa);
#ifdef HAVE_EC
    if (ec)
        EC_KEY_free(ec);
#endif

    if (result == NULL) {
        return PKEY_BADARG;
    } else {
        *pkey = result;
        return PKEY_OK;
    }
}

ERL_NIF_TERM pkey_sign_nif(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[])
{/* (Algorithm, Type, Data|{digest,Digest}, Key|#{}, Options) */
    int i;
    int sig_bin_alloc = 0;
    ERL_NIF_TERM ret;
    const EVP_MD *md = NULL;
    unsigned char md_value[EVP_MAX_MD_SIZE];
    EVP_PKEY *pkey = NULL;
#ifdef HAVE_EDDSA
    EVP_MD_CTX *mdctx = NULL;
#endif
#ifdef HAS_EVP_PKEY_CTX
    EVP_PKEY_CTX *ctx = NULL;
    size_t siglen;
#else
    int len;
    unsigned int siglen;
#endif
    PKeySignOptions sig_opt;
    ErlNifBinary sig_bin; /* signature */
    unsigned char *tbs; /* data to be signed */
    size_t tbslen;
    RSA *rsa = NULL;
    DSA *dsa = NULL;
#if defined(HAVE_EC)
    EC_KEY *ec = NULL;
#endif
/*char buf[1024];
enif_get_atom(env,argv[0],buf,1024,ERL_NIF_LATIN1); printf("algo=%s ",buf);
enif_get_atom(env,argv[1],buf,1024,ERL_NIF_LATIN1); printf("hash=%s ",buf);
printf("\r\n");
*/

#ifndef HAS_ENGINE_SUPPORT
    if (enif_is_map(env, argv[3]))
        return atom_notsup;
#endif

    i = get_pkey_sign_digest(env, argv[0], argv[1], argv[2], md_value, &md, &tbs, &tbslen);
    switch (i) {
    case PKEY_OK:
        break;
    case PKEY_NOTSUP:
        goto notsup;
    default:
        goto bad_arg;
    }

    i = get_pkey_sign_options(env, argv[0], argv[4], md, &sig_opt);
    switch (i) {
    case PKEY_OK:
        break;
    case PKEY_NOTSUP:
        goto notsup;
    default:
        goto bad_arg;
    }

    if (get_pkey_private_key(env, argv[0], argv[3], &pkey) != PKEY_OK)
        goto bad_arg;

#ifdef HAS_EVP_PKEY_CTX
    if ((ctx = EVP_PKEY_CTX_new(pkey, NULL)) == NULL)
        goto err;

    if (argv[0] != atom_eddsa) {
        if (EVP_PKEY_sign_init(ctx) != 1)
            goto err;
        if (md != NULL) {
            if (EVP_PKEY_CTX_set_signature_md(ctx, md) != 1)
                goto err;
        }
    }

    if (argv[0] == atom_rsa) {
        if (EVP_PKEY_CTX_set_rsa_padding(ctx, sig_opt.rsa_padding) != 1)
            goto err;
# ifdef HAVE_RSA_PKCS1_PSS_PADDING
	if (sig_opt.rsa_padding == RSA_PKCS1_PSS_PADDING) {
            if (sig_opt.rsa_mgf1_md != NULL) {
# ifdef HAVE_RSA_MGF1_MD
                if (EVP_PKEY_CTX_set_rsa_mgf1_md(ctx, sig_opt.rsa_mgf1_md) != 1)
                    goto err;
# else
                goto notsup;
# endif
            }
            if (sig_opt.rsa_pss_saltlen > -2) {
                if (EVP_PKEY_CTX_set_rsa_pss_saltlen(ctx, sig_opt.rsa_pss_saltlen) != 1)
                    goto err;
            }
        }
#endif
    }

    if (argv[0] == atom_eddsa) {
#ifdef HAVE_EDDSA
        if ((mdctx = EVP_MD_CTX_new()) == NULL)
            goto err;

        if (EVP_DigestSignInit(mdctx, NULL, NULL, NULL, pkey) != 1)
            goto err;
        if (EVP_DigestSign(mdctx, NULL, &siglen, tbs, tbslen) != 1)
            goto err;
        if (!enif_alloc_binary(siglen, &sig_bin))
            goto err;
        sig_bin_alloc = 1;

        if (EVP_DigestSign(mdctx, sig_bin.data, &siglen, tbs, tbslen) != 1)
            goto bad_key;
#else
        goto bad_arg;
#endif
    } else {
        if (EVP_PKEY_sign(ctx, NULL, &siglen, tbs, tbslen) != 1)
            goto err;
        if (!enif_alloc_binary(siglen, &sig_bin))
            goto err;
        sig_bin_alloc = 1;

        if (md != NULL) {
            ERL_VALGRIND_ASSERT_MEM_DEFINED(tbs, EVP_MD_size(md));
        }
        if (EVP_PKEY_sign(ctx, sig_bin.data, &siglen, tbs, tbslen) != 1)
            goto bad_key;
    }
#else
/*printf("Old interface\r\n");
 */
    if (argv[0] == atom_rsa) {
        if ((rsa = EVP_PKEY_get1_RSA(pkey)) == NULL)
            goto err;
        if ((len = RSA_size(rsa)) < 0)
            goto err;
        if (!enif_alloc_binary((size_t)len, &sig_bin))
            goto err;
        sig_bin_alloc = 1;

        if ((len = EVP_MD_size(md)) < 0)
            goto err;
        ERL_VALGRIND_ASSERT_MEM_DEFINED(tbs, len);

        if (RSA_sign(md->type, tbs, (unsigned int)len, sig_bin.data, &siglen, rsa) != 1)
            goto bad_key;
    } else if (argv[0] == atom_dss) {
        if ((dsa = EVP_PKEY_get1_DSA(pkey)) == NULL)
            goto err;
        if ((len = DSA_size(dsa)) < 0)
            goto err;
        if (!enif_alloc_binary((size_t)len, &sig_bin))
            goto err;
        sig_bin_alloc = 1;

        if ((len = EVP_MD_size(md)) < 0)
            goto err;
        ERL_VALGRIND_ASSERT_MEM_DEFINED(tbs, len);

        if (DSA_sign(md->type, tbs, len, sig_bin.data, &siglen, dsa) != 1)
            goto bad_key;
    } else if (argv[0] == atom_ecdsa) {
#if defined(HAVE_EC)
        if ((ec = EVP_PKEY_get1_EC_KEY(pkey)) == NULL)
            goto err;
        if ((len = ECDSA_size(ec)) < 0)
            goto err;
        if (!enif_alloc_binary((size_t)len, &sig_bin))
            goto err;
        sig_bin_alloc = 1;

        len = EVP_MD_size(md);
        ERL_VALGRIND_ASSERT_MEM_DEFINED(tbs, len);

        if (ECDSA_sign(md->type, tbs, len, sig_bin.data, &siglen, ec) != 1)
            goto bad_key;
#else
        goto notsup;
#endif
    } else {
        goto bad_arg;
    }
#endif

    ERL_VALGRIND_MAKE_MEM_DEFINED(sig_bin.data, siglen);
    if (siglen != sig_bin.size) {
        if (!enif_realloc_binary(&sig_bin, siglen))
            goto err;
        ERL_VALGRIND_ASSERT_MEM_DEFINED(sig_bin.data, siglen);
    }
    ret = enif_make_binary(env, &sig_bin);
    sig_bin_alloc = 0;
    goto done;

 bad_key:
    ret = atom_error;
    goto done;

 notsup:
    ret = atom_notsup;
    goto done;

 bad_arg:
 err:
    ret = enif_make_badarg(env);
    goto done;

 done:
    if (sig_bin_alloc)
        enif_release_binary(&sig_bin);
    if (rsa)
        RSA_free(rsa);
    if (dsa)
        DSA_free(dsa);
#ifdef HAVE_EC
    if (ec)
        EC_KEY_free(ec);
#endif
#ifdef HAS_EVP_PKEY_CTX
    if (ctx)
        EVP_PKEY_CTX_free(ctx);
#endif
    if (pkey)
        EVP_PKEY_free(pkey);

    return ret;
}

ERL_NIF_TERM pkey_verify_nif(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[])
{/* (Algorithm, Type, Data|{digest,Digest}, Signature, Key, Options) */
    int i;
    int result;
    const EVP_MD *md = NULL;
    unsigned char md_value[EVP_MAX_MD_SIZE];
    EVP_PKEY *pkey = NULL;
#ifdef HAS_EVP_PKEY_CTX
    EVP_PKEY_CTX *ctx = NULL;
#else
#endif
    PKeySignOptions sig_opt;
    ErlNifBinary sig_bin; /* signature */
    unsigned char *tbs; /* data to be signed */
    size_t tbslen;
    ERL_NIF_TERM ret;
    RSA *rsa = NULL;
    DSA *dsa = NULL;
#ifdef HAVE_EC
    EC_KEY *ec = NULL;
#endif
#ifdef HAVE_EDDSA
    EVP_MD_CTX *mdctx = NULL;
#endif

#ifndef HAS_ENGINE_SUPPORT
    if (enif_is_map(env, argv[4]))
        return atom_notsup;
#endif

    if (!enif_inspect_binary(env, argv[3], &sig_bin))
	return enif_make_badarg(env);

    i = get_pkey_sign_digest(env, argv[0], argv[1], argv[2], md_value, &md, &tbs, &tbslen);
    switch (i) {
    case PKEY_OK:
        break;
    case PKEY_NOTSUP:
        goto notsup;
    default:
        goto bad_arg;
    }

    i = get_pkey_sign_options(env, argv[0], argv[5], md, &sig_opt);
    switch (i) {
    case PKEY_OK:
        break;
    case PKEY_NOTSUP:
        goto notsup;
    default:
        goto bad_arg;
    }

    if (get_pkey_public_key(env, argv[0], argv[4], &pkey) != PKEY_OK) {
        goto bad_arg;
    }

#ifdef HAS_EVP_PKEY_CTX
/* printf("EVP interface\r\n");
 */
    if ((ctx = EVP_PKEY_CTX_new(pkey, NULL)) == NULL)
        goto err;

    if (argv[0] != atom_eddsa) {
        if (EVP_PKEY_verify_init(ctx) != 1)
            goto err;
        if (md != NULL) {
            if (EVP_PKEY_CTX_set_signature_md(ctx, md) != 1)
                goto err;
        }
    }

    if (argv[0] == atom_rsa) {
        if (EVP_PKEY_CTX_set_rsa_padding(ctx, sig_opt.rsa_padding) != 1)
            goto err;
        if (sig_opt.rsa_padding == RSA_PKCS1_PSS_PADDING) {
            if (sig_opt.rsa_mgf1_md != NULL) {
# ifdef HAVE_RSA_MGF1_MD
                if (EVP_PKEY_CTX_set_rsa_mgf1_md(ctx, sig_opt.rsa_mgf1_md) != 1)
                    goto err;
# else
                goto notsup;
# endif
            }
            if (sig_opt.rsa_pss_saltlen > -2) {
                if (EVP_PKEY_CTX_set_rsa_pss_saltlen(ctx, sig_opt.rsa_pss_saltlen) != 1)
                    goto err;
            }
        }
    }

    if (argv[0] == atom_eddsa) {
#ifdef HAVE_EDDSA
        if ((mdctx = EVP_MD_CTX_new()) == NULL)
            goto err;
        
        if (EVP_DigestVerifyInit(mdctx, NULL, NULL, NULL, pkey) != 1)
            goto err;

        result = EVP_DigestVerify(mdctx, sig_bin.data, sig_bin.size, tbs, tbslen);
#else
        goto bad_arg;
#endif
    } else {
        if (md != NULL) {
            ERL_VALGRIND_ASSERT_MEM_DEFINED(tbs, EVP_MD_size(md));
        }
        result = EVP_PKEY_verify(ctx, sig_bin.data, sig_bin.size, tbs, tbslen);
    }
#else
/*printf("Old interface\r\n");
*/
    if (tbslen > INT_MAX)
        goto bad_arg;
    if (sig_bin.size > INT_MAX)
        goto bad_arg;
    if (argv[0] == atom_rsa) {
        if ((rsa = EVP_PKEY_get1_RSA(pkey)) == NULL)
            goto err;
        result = RSA_verify(md->type, tbs, (unsigned int)tbslen, sig_bin.data, (unsigned int)sig_bin.size, rsa);
    } else if (argv[0] == atom_dss) {
        if ((dsa = EVP_PKEY_get1_DSA(pkey)) == NULL)
            goto err;
        result = DSA_verify(0, tbs, (int)tbslen, sig_bin.data, (int)sig_bin.size, dsa);
    } else if (argv[0] == atom_ecdsa) {
#if defined(HAVE_EC)
        if ((ec = EVP_PKEY_get1_EC_KEY(pkey)) == NULL)
            goto err;
        result = ECDSA_verify(EVP_MD_type(md), tbs, (int)tbslen, sig_bin.data, (int)sig_bin.size, ec);
#else
        goto notsup;
#endif
    } else {
        goto bad_arg;
    }
#endif

    ret = (result == 1 ? atom_true : atom_false);
    goto done;

 bad_arg:
 err:
    ret = enif_make_badarg(env);
    goto done;

 notsup:
    ret = atom_notsup;

 done:
#ifdef HAS_EVP_PKEY_CTX
    if (ctx)
        EVP_PKEY_CTX_free(ctx);
#endif
#ifdef HAVE_EDDSA
    if (mdctx)
        EVP_MD_CTX_free(mdctx);
#endif
    if (pkey)
        EVP_PKEY_free(pkey);
    if (rsa)
        RSA_free(rsa);
    if (dsa)
        DSA_free(dsa);
#ifdef HAVE_EC
    if (ec)
        EC_KEY_free(ec);
#endif

    return ret;
}

static int get_pkey_crypt_options(ErlNifEnv *env, ERL_NIF_TERM algorithm, ERL_NIF_TERM options,
				  PKeyCryptOptions *opt)
{
    ERL_NIF_TERM head, tail;
    const ERL_NIF_TERM *tpl_terms;
    int tpl_arity;
    const EVP_MD *opt_md;
    int i;

    if (!enif_is_list(env, options)) {
	return PKEY_BADARG;
    }

    /* defaults */
    if (algorithm == atom_rsa) {
	opt->rsa_mgf1_md = NULL;
	opt->rsa_oaep_label.data = NULL;
	opt->rsa_oaep_label.size = 0;
	opt->rsa_oaep_md = NULL;
	opt->rsa_padding = RSA_PKCS1_PADDING;
	opt->signature_md = NULL;
    }

    if (enif_is_empty_list(env, options)) {
	return PKEY_OK;
    }

    if (algorithm == atom_rsa) {
	tail = options;
	while (enif_get_list_cell(env, tail, &head, &tail)) {
	    if (enif_get_tuple(env, head, &tpl_arity, &tpl_terms) && tpl_arity == 2) {
		if (tpl_terms[0] == atom_rsa_padding
                    || tpl_terms[0] == atom_rsa_pad /* Compatibility */
                    ) {
		    if (tpl_terms[1] == atom_rsa_pkcs1_padding) {
			opt->rsa_padding = RSA_PKCS1_PADDING;
#ifdef HAVE_RSA_OAEP_PADDING
		    } else if (tpl_terms[1] == atom_rsa_pkcs1_oaep_padding) {
			opt->rsa_padding = RSA_PKCS1_OAEP_PADDING;
#endif
#ifdef HAVE_RSA_SSLV23_PADDING
		    } else if (tpl_terms[1] == atom_rsa_sslv23_padding) {
			opt->rsa_padding = RSA_SSLV23_PADDING;
#endif
		    } else if (tpl_terms[1] == atom_rsa_x931_padding) {
			opt->rsa_padding = RSA_X931_PADDING;
		    } else if (tpl_terms[1] == atom_rsa_no_padding) {
			opt->rsa_padding = RSA_NO_PADDING;
		    } else {
			return PKEY_BADARG;
		    }
		} else if (tpl_terms[0] == atom_signature_md && enif_is_atom(env, tpl_terms[1])) {
		    i = get_pkey_digest_type(env, algorithm, tpl_terms[1], &opt_md);
		    if (i != PKEY_OK) {
			return i;
		    }
		    opt->signature_md = opt_md;
		} else if (tpl_terms[0] == atom_rsa_mgf1_md && enif_is_atom(env, tpl_terms[1])) {
#ifndef HAVE_RSA_MGF1_MD
		    if (tpl_terms[1] != atom_sha)
			return PKEY_NOTSUP;
#endif
		    i = get_pkey_digest_type(env, algorithm, tpl_terms[1], &opt_md);
		    if (i != PKEY_OK) {
			return i;
		    }
		    opt->rsa_mgf1_md = opt_md;
		} else if (tpl_terms[0] == atom_rsa_oaep_label
			   && enif_inspect_binary(env, tpl_terms[1], &(opt->rsa_oaep_label))) {
#ifdef HAVE_RSA_OAEP_MD
		    continue;
#else
		    return PKEY_NOTSUP;
#endif
		} else if (tpl_terms[0] == atom_rsa_oaep_md && enif_is_atom(env, tpl_terms[1])) {
#ifndef HAVE_RSA_OAEP_MD
		    if (tpl_terms[1] != atom_sha)
			return PKEY_NOTSUP;
#endif
		    i = get_pkey_digest_type(env, algorithm, tpl_terms[1], &opt_md);
		    if (i != PKEY_OK) {
			return i;
		    }
		    opt->rsa_oaep_md = opt_md;
		} else {
		    return PKEY_BADARG;
		}
	    } else {
		return PKEY_BADARG;
	    }
	}
    } else {
	return PKEY_BADARG;
    }

    return PKEY_OK;
}

static size_t size_of_RSA(EVP_PKEY *pkey) {
    size_t tmplen;
    RSA *rsa = EVP_PKEY_get1_RSA(pkey);
    if (rsa == NULL) return 0;
    tmplen = RSA_size(rsa);
    RSA_free(rsa);
    return tmplen;
}

ERL_NIF_TERM pkey_crypt_nif(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[])
{/* (Algorithm, Data, PublKey=[E,N]|[E,N,D]|[E,N,D,P1,P2,E1,E2,C], Options, IsPrivate, IsEncrypt) */
    int i;
    EVP_PKEY *pkey;
#ifdef HAS_EVP_PKEY_CTX
    EVP_PKEY_CTX *ctx;
#else
    RSA *rsa;
#endif
    PKeyCryptOptions crypt_opt;
    ErlNifBinary in_bin, out_bin, tmp_bin;
    size_t outlen;
#ifdef HAVE_RSA_SSLV23_PADDING
    size_t tmplen;
#endif
    int is_private = (argv[4] == atom_true),
        is_encrypt = (argv[5] == atom_true);
    int algo_init = 0;

/* char algo[1024]; */

#ifndef HAS_ENGINE_SUPPORT
    if (enif_is_map(env, argv[2])) {
        return atom_notsup;
    }
#endif

    if (!enif_inspect_binary(env, argv[1], &in_bin)) {
	return enif_make_badarg(env);
    }

    i = get_pkey_crypt_options(env, argv[0], argv[3], &crypt_opt);
    if (i != PKEY_OK) {
	if (i == PKEY_NOTSUP)
	    return atom_notsup;
	else
	    return enif_make_badarg(env);
    }

    if (is_private) {
	if (get_pkey_private_key(env, argv[0], argv[2], &pkey) != PKEY_OK) {
	    return enif_make_badarg(env);
	}
    } else {
	if (get_pkey_public_key(env, argv[0], argv[2], &pkey) != PKEY_OK) {
	    return enif_make_badarg(env);
	}
    }

    out_bin.data = NULL;
    out_bin.size = 0;
    tmp_bin.data = NULL;
    tmp_bin.size = 0;

#ifdef HAS_EVP_PKEY_CTX
    ctx = EVP_PKEY_CTX_new(pkey, NULL);
    if (!ctx) goto badarg;

/* enif_get_atom(env,argv[0],algo,1024,ERL_NIF_LATIN1);  */

    if (is_private) {
        if (is_encrypt) {
            /* private encrypt */
            if ((algo_init=EVP_PKEY_sign_init(ctx)) <= 0) {
                /* fprintf(stderr,"BADARG %s private encrypt algo_init=%d %s:%d\r\n", algo, algo_init, __FILE__, __LINE__); */
                goto badarg;
            }
        } else {
            /* private decrypt */
            if ((algo_init=EVP_PKEY_decrypt_init(ctx)) <= 0) {
                /* fprintf(stderr,"BADARG %s private decrypt algo_init=%d %s:%d\r\n", algo, algo_init, __FILE__, __LINE__); */
                goto badarg;
            }
        }
    } else {
        if (is_encrypt) {
            /* public encrypt */
            if ((algo_init=EVP_PKEY_encrypt_init(ctx)) <= 0) {
                /* fprintf(stderr,"BADARG %s public encrypt algo_init=%d %s:%d\r\n", algo,algo_init,__FILE__, __LINE__); */
                goto badarg;
            }
        } else {
            /* public decrypt */
            if ((algo_init=EVP_PKEY_verify_recover_init(ctx)) <= 0) {
                /* fprintf(stderr,"BADARG %s public decrypt algo_init=%d %s:%d\r\n", algo,algo_init,__FILE__, __LINE__); */
                goto badarg;
            }
        }
    }

    if (argv[0] == atom_rsa) {
	if (crypt_opt.signature_md != NULL
	    && EVP_PKEY_CTX_set_signature_md(ctx, crypt_opt.signature_md) <= 0)
		goto badarg;
#ifdef HAVE_RSA_SSLV23_PADDING
	if (crypt_opt.rsa_padding == RSA_SSLV23_PADDING) {
	    if (is_encrypt) {
                tmplen = size_of_RSA(pkey);
                if (tmplen == 0) goto badarg;
		if (!enif_alloc_binary(tmplen, &tmp_bin)) goto badarg;
		if (RSA_padding_add_SSLv23(tmp_bin.data, tmplen, in_bin.data, in_bin.size) <= 0)
		    goto badarg;
		in_bin = tmp_bin;
	    }
	    if (EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_NO_PADDING) <= 0) goto badarg;
	} else
#endif
                {
	    if (EVP_PKEY_CTX_set_rsa_padding(ctx, crypt_opt.rsa_padding) <= 0) goto badarg;
        }
#ifdef HAVE_RSA_OAEP_MD
	if (crypt_opt.rsa_padding == RSA_PKCS1_OAEP_PADDING) {
	    if (crypt_opt.rsa_oaep_md != NULL
		&& EVP_PKEY_CTX_set_rsa_oaep_md(ctx, crypt_opt.rsa_oaep_md) <= 0)
		goto badarg;
	    if (crypt_opt.rsa_mgf1_md != NULL
		&& EVP_PKEY_CTX_set_rsa_mgf1_md(ctx, crypt_opt.rsa_mgf1_md) <= 0) goto badarg;
	    if (crypt_opt.rsa_oaep_label.data != NULL && crypt_opt.rsa_oaep_label.size > 0) {
		unsigned char *label_copy = NULL;
		label_copy = OPENSSL_malloc(crypt_opt.rsa_oaep_label.size);
		if (label_copy == NULL) goto badarg;
		memcpy((void *)(label_copy), (const void *)(crypt_opt.rsa_oaep_label.data),
		       crypt_opt.rsa_oaep_label.size);
		if (EVP_PKEY_CTX_set0_rsa_oaep_label(ctx, label_copy,
						     crypt_opt.rsa_oaep_label.size) <= 0) {
		    OPENSSL_free(label_copy);
		    label_copy = NULL;
		    goto badarg;
		}
	    }
	}
#endif
    }

    if (is_private) {
	if (is_encrypt) {
	    /* private_encrypt */
	    i = EVP_PKEY_sign(ctx, NULL, &outlen, in_bin.data, in_bin.size);
	} else {
	    /* private_decrypt */
	    i = EVP_PKEY_decrypt(ctx, NULL, &outlen, in_bin.data, in_bin.size);
	}
    } else {
	if (is_encrypt) {
	    /* public_encrypt */
	    i = EVP_PKEY_encrypt(ctx, NULL, &outlen, in_bin.data, in_bin.size);
	} else {
	    /* public_decrypt */
	    i = EVP_PKEY_verify_recover(ctx, NULL, &outlen, in_bin.data, in_bin.size);
	}
    }
    /* fprintf(stderr,"i = %d %s:%d\r\n", i, __FILE__, __LINE__); */

    if (i != 1) goto badarg;

    enif_alloc_binary(outlen, &out_bin);

    if (is_private) {
	if (is_encrypt) {
	    /* private_encrypt */
	    i = EVP_PKEY_sign(ctx, out_bin.data, &outlen, in_bin.data, in_bin.size);
	} else {
	    /* private_decrypt */
	    i = EVP_PKEY_decrypt(ctx, out_bin.data, &outlen, in_bin.data, in_bin.size);
	}
    } else {
	if (is_encrypt) {
	    /* public_encrypt */
	    i = EVP_PKEY_encrypt(ctx, out_bin.data, &outlen, in_bin.data, in_bin.size);
	} else {
	    /* public_decrypt */
	    i = EVP_PKEY_verify_recover(ctx, out_bin.data, &outlen, in_bin.data, in_bin.size);
	}
    }

#else
    /* Non-EVP cryptolib. Only support RSA */

    if (argv[0] != atom_rsa) {
        algo_init = -2;         /* exitcode: notsup */
        goto badarg;
    }
    rsa = EVP_PKEY_get1_RSA(pkey);
    enif_alloc_binary(RSA_size(rsa), &out_bin);

    if (is_private) {
        if (is_encrypt) {
            /* non-evp rsa private encrypt */
            ERL_VALGRIND_ASSERT_MEM_DEFINED(in_bin.data,in_bin.size);
            i = RSA_private_encrypt(in_bin.size, in_bin.data,
                                    out_bin.data, rsa, crypt_opt.rsa_padding);
            if (i > 0) {
                ERL_VALGRIND_MAKE_MEM_DEFINED(out_bin.data, i);
            }
        } else {
            /* non-evp rsa private decrypt */
            i = RSA_private_decrypt(in_bin.size, in_bin.data,
                                    out_bin.data, rsa, crypt_opt.rsa_padding);
            if (i > 0) {
                ERL_VALGRIND_MAKE_MEM_DEFINED(out_bin.data, i);
                enif_realloc_binary(&out_bin, i);
            }
        }
    } else {
        if (is_encrypt) {
            /* non-evp rsa public encrypt */
            ERL_VALGRIND_ASSERT_MEM_DEFINED(in_bin.data,in_bin.size);
            i = RSA_public_encrypt(in_bin.size, in_bin.data,
                                   out_bin.data, rsa, crypt_opt.rsa_padding);
            if (i > 0) {
                ERL_VALGRIND_MAKE_MEM_DEFINED(out_bin.data, i);
	}
        } else {
            /* non-evp rsa public decrypt */
            i = RSA_public_decrypt(in_bin.size, in_bin.data,
                                   out_bin.data, rsa, crypt_opt.rsa_padding);
            if (i > 0) {
                ERL_VALGRIND_MAKE_MEM_DEFINED(out_bin.data, i);
                enif_realloc_binary(&out_bin, i);
            }
        }
    }

    outlen = i;
    RSA_free(rsa);
#endif

    if ((i > 0) && argv[0] == atom_rsa && !is_encrypt) {
#ifdef HAVE_RSA_SSLV23_PADDING
	if (crypt_opt.rsa_padding == RSA_SSLV23_PADDING) {
	    unsigned char *p;
            tmplen = size_of_RSA(pkey);
	    if (tmplen == 0) goto badarg;
	    if (!enif_alloc_binary(tmplen, &tmp_bin))
                goto badarg;
	    p = out_bin.data;
	    p++;
	    i = RSA_padding_check_SSLv23(tmp_bin.data, tmplen, p, out_bin.size - 1, tmplen);
	    if (i >= 0) {
		outlen = i;
		in_bin = out_bin;
		out_bin = tmp_bin;
		tmp_bin = in_bin;
		i = 1;
	    }
	}
#endif
    }

    if (tmp_bin.data != NULL) {
	enif_release_binary(&tmp_bin);
    }

#ifdef HAS_EVP_PKEY_CTX
    EVP_PKEY_CTX_free(ctx);
#else
#endif
    EVP_PKEY_free(pkey);
    if (i > 0) {
	ERL_VALGRIND_MAKE_MEM_DEFINED(out_bin.data, outlen);
	if (outlen != out_bin.size) {
	    enif_realloc_binary(&out_bin, outlen);
	    ERL_VALGRIND_ASSERT_MEM_DEFINED(out_bin.data, outlen);
	}
	return enif_make_binary(env, &out_bin);
    } else {
	enif_release_binary(&out_bin);
	return atom_error;
    }

 badarg:
    if (out_bin.data != NULL) {
	enif_release_binary(&out_bin);
    }
    if (tmp_bin.data != NULL) {
	enif_release_binary(&tmp_bin);
    }
#ifdef HAS_EVP_PKEY_CTX
    EVP_PKEY_CTX_free(ctx);
#else
#endif
    EVP_PKEY_free(pkey);
    if (algo_init == -2)
        return atom_notsup;
    else
        return enif_make_badarg(env);
}

ERL_NIF_TERM privkey_to_pubkey_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{ /* (Algorithm, PrivKey | KeyMap) */
    EVP_PKEY *pkey;
    ERL_NIF_TERM alg = argv[0];
    ERL_NIF_TERM result[8];
    if (get_pkey_private_key(env, alg, argv[1], &pkey) != PKEY_OK) {
	return enif_make_badarg(env);
    }

    if (alg == atom_rsa) {
        const BIGNUM *n = NULL, *e = NULL, *d = NULL;
        RSA *rsa = EVP_PKEY_get1_RSA(pkey);
        if (rsa) {
            RSA_get0_key(rsa, &n, &e, &d);
            result[0] = bin_from_bn(env, e);  // Exponent E
            result[1] = bin_from_bn(env, n);  // Modulus N = p*q
            RSA_free(rsa);
            EVP_PKEY_free(pkey);
            return enif_make_list_from_array(env, result, 2);
        }

    } else if (argv[0] == atom_dss) {
        const BIGNUM *p = NULL, *q = NULL, *g = NULL, *pub_key = NULL;
        DSA *dsa = EVP_PKEY_get1_DSA(pkey);
        if (dsa) {
            DSA_get0_pqg(dsa, &p, &q, &g);
            DSA_get0_key(dsa, &pub_key, NULL);
            result[0] = bin_from_bn(env, p);
            result[1] = bin_from_bn(env, q);
            result[2] = bin_from_bn(env, g);
            result[3] = bin_from_bn(env, pub_key);
	    DSA_free(dsa);
            EVP_PKEY_free(pkey);
            return enif_make_list_from_array(env, result, 4);
        }

    } else if (argv[0] == atom_ecdsa) {
#if defined(HAVE_EC)
        /* not yet implemented
          EC_KEY *ec = EVP_PKEY_get1_EC_KEY(pkey);
          if (ec) {
          / * Example of result:
               {
                 Curve =  {Field, Prime, Point, Order, CoFactor} =
                    {
                      Field =  {prime_field,<<255,...,255>>},
                      Prime = {<<255,...,252>>,
                               <<90,...,75>>,
                               <<196,...,144>>
                              },
                      Point =    <<4,...,245>>,
                      Order =    <<255,...,81>>,
                      CoFactor = <<1>>
                    },
                Key = <<151,...,62>>
                }
              or
              {
                Curve =
                    {characteristic_two_field,
                     M,
                     Basis = {tpbasis, _}
                           | {ppbasis, k1, k2, k3}
                    },
                Key
               }
        * /
            EVP_PKEY_free(pkey);
            return enif_make_list_from_array(env, ..., ...);
        */
#endif
    }

    if (pkey) EVP_PKEY_free(pkey);
    return enif_make_badarg(env);
}