int aes256cbc_dec(const unsigned char *inBuf, size_t inLen, unsigned char *outBuf, unsigned char *key, unsigned char* iv) { const EVP_CIPHER *cipher=NULL; //unsigned char salt[PKCS5_SALT_LEN], key[EVP_MAX_KEY_LENGTH], iv[EVP_MAX_IV_LENGTH]; unsigned char buf[KEY_SIZE / 8], *data = NULL; BIO *benc=NULL, *out=NULL, *wbio=NULL; EVP_CIPHER_CTX *ctx = NULL; BUF_MEM *memptr = NULL; int ret = 1, i = 0; long dataLength = 0; int old_fmode = _fmode; for(i = 0; i < sizeof(buf); ++i) buf[i] = i; apps_startup(); if (!load_config(bio_err, NULL)) goto aes_dec_end; cipher=EVP_get_cipherbyname("aes-256-cbc"); //out = BIO_new_mem_buf(buf, BUFFER_SIZE); out = BIO_new(BIO_s_mem()); wbio = out; //EVP_BytesToKey(cipher, dgst, salt, pass, passLength, DECRYPT, key, iv); if ((benc=BIO_new(BIO_f_cipher())) == NULL) goto aes_dec_end; BIO_get_cipher_ctx(benc, &ctx); if (!EVP_CipherInit_ex(ctx, cipher, NULL, NULL, NULL, DECRYPT)) { BIO_printf(bio_err, "Error setting cipher %s\n", EVP_CIPHER_name(cipher)); ERR_print_errors(bio_err); goto aes_dec_end; } //if (no_padding) // EVP_CIPHER_CTX_set_padding(ctx, 0); if (!EVP_CipherInit_ex(ctx, NULL, NULL, key, iv, DECRYPT)) { BIO_printf(bio_err, "Error setting cipher %s\n", EVP_CIPHER_name(cipher)); ERR_print_errors(bio_err); goto aes_dec_end; } wbio = BIO_push(benc, wbio); BIO_write(wbio, inBuf, inLen); ret = BIO_get_mem_data(out, &data); if(ret <= 0) { BIO_printf(bio_err, "Error decrypt cipher %s: %d\n", EVP_CIPHER_name(cipher), ret); ERR_print_errors(bio_err); goto aes_dec_end; } for(i = 0; i < ret; ++i) outBuf[i] = data[i]; aes_dec_end: if (benc != NULL) BIO_free(benc); if (out != NULL) BIO_free(out); apps_shutdown(old_fmode); return ret; }
static int cipher_name_cmp(const void *a, const void *b) { const EVP_CIPHER *const *cipher_a = a; const EVP_CIPHER *const *cipher_b = b; const char *cipher_name_a = translate_cipher_name_to_openvpn(EVP_CIPHER_name(*cipher_a)); const char *cipher_name_b = translate_cipher_name_to_openvpn(EVP_CIPHER_name(*cipher_b)); return strcmp(cipher_name_a, cipher_name_b); }
int main(int argc, char **argv) { int i; char *names[] = { "sms4-ecb", "sms4-cbc", "sms4-cfb", "sms4-ofb", "sms4-ctr", }; const EVP_CIPHER *cipher; OpenSSL_add_all_ciphers(); printf("%s new ciphers:\n\n", OPENSSL_VERSION_TEXT); for (i = 0; i < sizeof(names)/sizeof(names[i]); i++) { if (!(cipher = EVP_get_cipherbyname(names[i]))) { fprintf(stderr, "cipher \"%s\" is not supported\n", names[i]); continue; } printf(" cipher nid : %d\n", EVP_CIPHER_nid(cipher)); printf(" cipher name : %s\n", EVP_CIPHER_name(cipher)); printf(" block size : %d\n", EVP_CIPHER_block_size(cipher)); printf(" key length : %d\n", EVP_CIPHER_key_length(cipher)); printf(" iv length : %d\n", EVP_CIPHER_iv_length(cipher)); printf(" flags : 0x%016lx\n", EVP_CIPHER_flags(cipher)); printf("\n"); } return 0; }
const char * cipher_kt_name (const EVP_CIPHER *cipher_kt) { if (NULL == cipher_kt) return "[null-cipher]"; return EVP_CIPHER_name (cipher_kt); }
void list_ciphers(const EVP_CIPHER *c, const char *from, const char *to, void *arg) { static char *last = NULL; char *current; if(c) { current = (char *) EVP_CIPHER_name(c); if(last == NULL) last = current; else if(strcasecmp(last, current) >= 0) return; else last = current; fprintf(stderr, " %s\n", current); } else if(from && to) { current = (char *) from; if(last == NULL) last = current; else if(strcasecmp(last, from) >= 0) return; else last = (char *) from; fprintf(stderr, " %s => %s\n", from, to); } }
static VALUE ossl_cipher_name(VALUE self) { EVP_CIPHER_CTX *ctx; GetCipher(self, ctx); return rb_str_new2(EVP_CIPHER_name(EVP_CIPHER_CTX_cipher(ctx))); }
static int KA_CTX_print_private(BIO *out, const KA_CTX *ctx, int indent) { if (ctx) { if (!BIO_indent(out, indent, 80) || !BIO_printf(out, "Key Agreement Parameters:\n")) return 0; if (ctx->key) if (ctx->shared_secret) { /* If we have a shared secret, we also must have a private key * which we can print. This is a bit clumsy but unfortunately * OpenSSL doesn't offer a function to check whether or not an * EVP_PKEY contains a private key. */ if (!EVP_PKEY_print_private(out, ctx->key, indent+4, NULL)) return 0; } else { if (!EVP_PKEY_print_params(out, ctx->key, indent+4, NULL)) return 0; } else { if (!BIO_indent(out, indent+4, 80) || !BIO_printf(out, "<ABSENT>\n")) return 0; } if (!BIO_indent(out, indent, 80)) return 0; if (ctx->cipher) { if (!BIO_printf(out, "Cipher: %s\n", EVP_CIPHER_name(ctx->cipher))) return 0; } else if (!BIO_printf(out, "Cipher: %s\n", "<ABSENT>")) return 0; if (!BIO_indent(out, indent, 80)) return 0; if (ctx->md) { if (!BIO_printf(out, "Message Digest: %s\n", EVP_MD_name(ctx->md))) return 0; } else if (!BIO_printf(out, "Message Digest: %s\n", "<ABSENT>")) return 0; if (!BIO_indent(out, indent, 80) || !BIO_printf(out, "Shared Secret:\n") || !BUF_MEM_print(out, ctx->shared_secret, indent+4) || !BIO_indent(out, indent, 80) || !BIO_printf(out, "K_enc:\n") || !BUF_MEM_print(out, ctx->k_enc, indent+4) || !BIO_indent(out, indent, 80) || !BIO_printf(out, "K_mac:\n") || !BUF_MEM_print(out, ctx->k_mac, indent+4)) return 0; } else { if (!BIO_indent(out, indent, 80) || !BIO_printf(out, "<ABSENT>\n")) return 0; } return 1; }
/* evp_cipher method */ static LUA_FUNCTION(openssl_cipher_info) { EVP_CIPHER *cipher = CHECK_OBJECT(1, EVP_CIPHER, "openssl.evp_cipher"); lua_newtable(L); AUXILIAR_SET(L, -1, "name", EVP_CIPHER_name(cipher), string); AUXILIAR_SET(L, -1, "block_size", EVP_CIPHER_block_size(cipher), integer); AUXILIAR_SET(L, -1, "key_length", EVP_CIPHER_key_length(cipher), integer); AUXILIAR_SET(L, -1, "iv_length", EVP_CIPHER_iv_length(cipher), integer); AUXILIAR_SET(L, -1, "flags", EVP_CIPHER_flags(cipher), integer); AUXILIAR_SET(L, -1, "mode", EVP_CIPHER_mode(cipher), integer); return 1; }
static void list_cipher_fn(const EVP_CIPHER *c, const char *from, const char *to, void *arg) { if (c) BIO_printf(arg, "%s\n", EVP_CIPHER_name(c)); else { if (!from) from = "<undefined>"; if (!to) to = "<undefined>"; BIO_printf(arg, "%s => %s\n", from, to); } }
int aes_init (crypt_data_t* crypt_data, crypt_init_t crypt_init) { const EVP_CIPHER* cipher = 0; switch (crypt_data->keysize) { case 16: cipher = EVP_aes_128_cbc (); break; case 24: cipher = EVP_aes_192_cbc (); break; case 32: cipher = EVP_aes_256_cbc (); break; default: fprintf (stderr, "Invalid key size.\n"); return -1; } EVP_CIPHER_CTX_init (&crypt_data->ctx); if (!crypt_init (&crypt_data->ctx, cipher, NULL, crypt_data->keybuf, crypt_data->ivbuf)) { fprintf (stderr, "OpenSSL initialization failed.\n"); return 1; } if (verbose) { fprintf (stderr, "EVP Initialized\n Algorithm: %s\n", EVP_CIPHER_name (EVP_CIPHER_CTX_cipher (&crypt_data->ctx))); fprintf (stderr, " IV: "); pp_buf (stderr, crypt_data->ivbuf, crypt_data->ivsize, 16, 2); fprintf (stderr, " Key: "); pp_buf (stderr, crypt_data->keybuf, crypt_data->keysize, 16, 2); } crypt_data->buf_size = INBUFSIZE; crypt_data->out_buf = (char*)malloc (crypt_data->buf_size + EVP_CIPHER_CTX_block_size (&crypt_data->ctx)); crypt_data->in_buf = (char*)malloc (crypt_data->buf_size); if (!crypt_data->out_buf || !crypt_data->in_buf) { fprintf (stderr, "Unable to allocate memory.\n"); return 1; } return 0; }
void CryptStream::_writeHeader () { assert (_mode == WRITE); assert (_file_bio); // Operate on _file_bio char buf[header_buf_size+1]; // Write this header directly to the file, without encoding or encryption const int offset = header_buf_size; std::string hexIV = uc2hex((const unsigned char*)_iv.c_str(), _iv.length()); int r = snprintf (buf, header_buf_size-1, "*167110* # v:%i # c:%.1i # e:%.1i # o:%i # ciph:%.30s # iv:%.256s # count:%i #", this->_version, isEncrypted(), isEncoded(), offset, EVP_CIPHER_name(_cipher), hexIV.c_str(), _pbkdfIterationCount); memset(buf+r, '*', header_buf_size-r-1); buf[header_buf_size-1] = '\n'; BIO_write(_file_bio, buf, header_buf_size); }
void openssl_evp_keyiv() { int i; const EVP_MD *md; const EVP_CIPHER *type; unsigned char salt[32], data[COMM_LEN], *key, *iv; md = EVP_md5(); printf("\nEVP_Md info: type[%d], ", EVP_MD_type(md)); printf("nid[%d], ", EVP_MD_nid(md)); printf("name[%s], ", EVP_MD_name(md)); printf("pkey type[%d], ", EVP_MD_pkey_type(md)); printf("size[%d], ", EVP_MD_size(md)); printf("block size[%d], ", EVP_MD_block_size(md)); type = EVP_des_ecb(); printf("\nEVP_ECB info: encrypto nid[%d], ", EVP_CIPHER_nid(type)); printf("name[%s], ", EVP_CIPHER_name(type)); printf("bock size[%d]", EVP_CIPHER_block_size(type)); key = (unsigned char *)malloc(EVP_CIPHER_key_length(type)); iv = (unsigned char *)malloc(EVP_CIPHER_iv_length(type)); for (i = 0; i < COMM_LEN; i++) memset(&data[i], i, 1); for (i = 0; i < 32; i++) memset(&salt[i], i, 1); EVP_BytesToKey(type, md, salt, data, COMM_LEN, 2, key, iv); printf("\nEVP_key value: "); for (i = 0; i < EVP_CIPHER_key_length(type); i++) printf("%x ", key[i]); printf("\nEVP_iv value: "); for (i = 0; i < EVP_CIPHER_iv_length(type); i++) printf("%x ", iv[i]); printf("\n"); }
int enc_main(int argc, char **argv) { static const char magic[] = "Salted__"; char mbuf[sizeof magic - 1]; char *strbuf = NULL, *pass = NULL; unsigned char *buff = NULL; int bsize = BSIZE; int ret = 1, inl; unsigned char key[EVP_MAX_KEY_LENGTH], iv[EVP_MAX_IV_LENGTH]; unsigned char salt[PKCS5_SALT_LEN]; #ifdef ZLIB BIO *bzl = NULL; #endif EVP_CIPHER_CTX *ctx = NULL; const EVP_MD *dgst = NULL; BIO *in = NULL, *out = NULL, *b64 = NULL, *benc = NULL; BIO *rbio = NULL, *wbio = NULL; #define PROG_NAME_SIZE 39 char pname[PROG_NAME_SIZE + 1]; int i; if (single_execution) { if (pledge("stdio rpath wpath cpath tty", NULL) == -1) { perror("pledge"); exit(1); } } memset(&enc_config, 0, sizeof(enc_config)); enc_config.enc = 1; /* first check the program name */ program_name(argv[0], pname, sizeof(pname)); if (strcmp(pname, "base64") == 0) enc_config.base64 = 1; #ifdef ZLIB if (strcmp(pname, "zlib") == 0) enc_config.do_zlib = 1; #endif enc_config.cipher = EVP_get_cipherbyname(pname); #ifdef ZLIB if (!enc_config.do_zlib && !enc_config.base64 && enc_config.cipher == NULL && strcmp(pname, "enc") != 0) #else if (!enc_config.base64 && enc_config.cipher == NULL && strcmp(pname, "enc") != 0) #endif { BIO_printf(bio_err, "%s is an unknown cipher\n", pname); goto end; } if (options_parse(argc, argv, enc_options, NULL, NULL) != 0) { enc_usage(); goto end; } if (enc_config.keyfile != NULL) { static char buf[128]; FILE *infile; infile = fopen(enc_config.keyfile, "r"); if (infile == NULL) { BIO_printf(bio_err, "unable to read key from '%s'\n", enc_config.keyfile); goto end; } buf[0] = '\0'; if (!fgets(buf, sizeof buf, infile)) { BIO_printf(bio_err, "unable to read key from '%s'\n", enc_config.keyfile); fclose(infile); goto end; } fclose(infile); i = strlen(buf); if ((i > 0) && ((buf[i - 1] == '\n') || (buf[i - 1] == '\r'))) buf[--i] = '\0'; if ((i > 0) && ((buf[i - 1] == '\n') || (buf[i - 1] == '\r'))) buf[--i] = '\0'; if (i < 1) { BIO_printf(bio_err, "zero length password\n"); goto end; } enc_config.keystr = buf; } if (enc_config.md != NULL && (dgst = EVP_get_digestbyname(enc_config.md)) == NULL) { BIO_printf(bio_err, "%s is an unsupported message digest type\n", enc_config.md); goto end; } if (dgst == NULL) { dgst = EVP_md5(); /* XXX */ } if (enc_config.bufsize != NULL) { char *p = enc_config.bufsize; unsigned long n; /* XXX - provide an OPTION_ARG_DISKUNIT. */ for (n = 0; *p != '\0'; p++) { i = *p; if ((i <= '9') && (i >= '0')) n = n * 10 + i - '0'; else if (i == 'k') { n *= 1024; p++; break; } } if (*p != '\0') { BIO_printf(bio_err, "invalid 'bufsize' specified.\n"); goto end; } /* It must be large enough for a base64 encoded line. */ if (enc_config.base64 && n < 80) n = 80; bsize = (int)n; if (enc_config.verbose) BIO_printf(bio_err, "bufsize=%d\n", bsize); } strbuf = malloc(SIZE); buff = malloc(EVP_ENCODE_LENGTH(bsize)); if ((buff == NULL) || (strbuf == NULL)) { BIO_printf(bio_err, "malloc failure %ld\n", (long) EVP_ENCODE_LENGTH(bsize)); goto end; } in = BIO_new(BIO_s_file()); out = BIO_new(BIO_s_file()); if ((in == NULL) || (out == NULL)) { ERR_print_errors(bio_err); goto end; } if (enc_config.debug) { BIO_set_callback(in, BIO_debug_callback); BIO_set_callback(out, BIO_debug_callback); BIO_set_callback_arg(in, (char *) bio_err); BIO_set_callback_arg(out, (char *) bio_err); } if (enc_config.inf == NULL) { if (enc_config.bufsize != NULL) setvbuf(stdin, (char *) NULL, _IONBF, 0); BIO_set_fp(in, stdin, BIO_NOCLOSE); } else { if (BIO_read_filename(in, enc_config.inf) <= 0) { perror(enc_config.inf); goto end; } } if (!enc_config.keystr && enc_config.passarg) { if (!app_passwd(bio_err, enc_config.passarg, NULL, &pass, NULL)) { BIO_printf(bio_err, "Error getting password\n"); goto end; } enc_config.keystr = pass; } if (enc_config.keystr == NULL && enc_config.cipher != NULL && enc_config.hkey == NULL) { for (;;) { char buf[200]; int retval; retval = snprintf(buf, sizeof buf, "enter %s %s password:"******"encryption" : "decryption"); if ((size_t)retval >= sizeof buf) { BIO_printf(bio_err, "Password prompt too long\n"); goto end; } strbuf[0] = '\0'; i = EVP_read_pw_string((char *)strbuf, SIZE, buf, enc_config.enc); if (i == 0) { if (strbuf[0] == '\0') { ret = 1; goto end; } enc_config.keystr = strbuf; break; } if (i < 0) { BIO_printf(bio_err, "bad password read\n"); goto end; } } } if (enc_config.outf == NULL) { BIO_set_fp(out, stdout, BIO_NOCLOSE); if (enc_config.bufsize != NULL) setvbuf(stdout, (char *)NULL, _IONBF, 0); } else { if (BIO_write_filename(out, enc_config.outf) <= 0) { perror(enc_config.outf); goto end; } } rbio = in; wbio = out; #ifdef ZLIB if (do_zlib) { if ((bzl = BIO_new(BIO_f_zlib())) == NULL) goto end; if (enc) wbio = BIO_push(bzl, wbio); else rbio = BIO_push(bzl, rbio); } #endif if (enc_config.base64) { if ((b64 = BIO_new(BIO_f_base64())) == NULL) goto end; if (enc_config.debug) { BIO_set_callback(b64, BIO_debug_callback); BIO_set_callback_arg(b64, (char *) bio_err); } if (enc_config.olb64) BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL); if (enc_config.enc) wbio = BIO_push(b64, wbio); else rbio = BIO_push(b64, rbio); } if (enc_config.cipher != NULL) { /* * Note that keystr is NULL if a key was passed on the command * line, so we get no salt in that case. Is this a bug? */ if (enc_config.keystr != NULL) { /* * Salt handling: if encrypting generate a salt and * write to output BIO. If decrypting read salt from * input BIO. */ unsigned char *sptr; if (enc_config.nosalt) sptr = NULL; else { if (enc_config.enc) { if (enc_config.hsalt) { if (!set_hex(enc_config.hsalt, salt, sizeof salt)) { BIO_printf(bio_err, "invalid hex salt value\n"); goto end; } } else arc4random_buf(salt, sizeof(salt)); /* * If -P option then don't bother * writing */ if ((enc_config.printkey != 2) && (BIO_write(wbio, magic, sizeof magic - 1) != sizeof magic - 1 || BIO_write(wbio, (char *) salt, sizeof salt) != sizeof salt)) { BIO_printf(bio_err, "error writing output file\n"); goto end; } } else if (BIO_read(rbio, mbuf, sizeof mbuf) != sizeof mbuf || BIO_read(rbio, (unsigned char *) salt, sizeof salt) != sizeof salt) { BIO_printf(bio_err, "error reading input file\n"); goto end; } else if (memcmp(mbuf, magic, sizeof magic - 1)) { BIO_printf(bio_err, "bad magic number\n"); goto end; } sptr = salt; } EVP_BytesToKey(enc_config.cipher, dgst, sptr, (unsigned char *)enc_config.keystr, strlen(enc_config.keystr), 1, key, iv); /* * zero the complete buffer or the string passed from * the command line bug picked up by Larry J. Hughes * Jr. <*****@*****.**> */ if (enc_config.keystr == strbuf) explicit_bzero(enc_config.keystr, SIZE); else explicit_bzero(enc_config.keystr, strlen(enc_config.keystr)); } if (enc_config.hiv != NULL && !set_hex(enc_config.hiv, iv, sizeof iv)) { BIO_printf(bio_err, "invalid hex iv value\n"); goto end; } if (enc_config.hiv == NULL && enc_config.keystr == NULL && EVP_CIPHER_iv_length(enc_config.cipher) != 0) { /* * No IV was explicitly set and no IV was generated * during EVP_BytesToKey. Hence the IV is undefined, * making correct decryption impossible. */ BIO_printf(bio_err, "iv undefined\n"); goto end; } if (enc_config.hkey != NULL && !set_hex(enc_config.hkey, key, sizeof key)) { BIO_printf(bio_err, "invalid hex key value\n"); goto end; } if ((benc = BIO_new(BIO_f_cipher())) == NULL) goto end; /* * Since we may be changing parameters work on the encryption * context rather than calling BIO_set_cipher(). */ BIO_get_cipher_ctx(benc, &ctx); if (!EVP_CipherInit_ex(ctx, enc_config.cipher, NULL, NULL, NULL, enc_config.enc)) { BIO_printf(bio_err, "Error setting cipher %s\n", EVP_CIPHER_name(enc_config.cipher)); ERR_print_errors(bio_err); goto end; } if (enc_config.nopad) EVP_CIPHER_CTX_set_padding(ctx, 0); if (!EVP_CipherInit_ex(ctx, NULL, NULL, key, iv, enc_config.enc)) { BIO_printf(bio_err, "Error setting cipher %s\n", EVP_CIPHER_name(enc_config.cipher)); ERR_print_errors(bio_err); goto end; } if (enc_config.debug) { BIO_set_callback(benc, BIO_debug_callback); BIO_set_callback_arg(benc, (char *) bio_err); } if (enc_config.printkey) { if (!enc_config.nosalt) { printf("salt="); for (i = 0; i < (int) sizeof(salt); i++) printf("%02X", salt[i]); printf("\n"); } if (enc_config.cipher->key_len > 0) { printf("key="); for (i = 0; i < enc_config.cipher->key_len; i++) printf("%02X", key[i]); printf("\n"); } if (enc_config.cipher->iv_len > 0) { printf("iv ="); for (i = 0; i < enc_config.cipher->iv_len; i++) printf("%02X", iv[i]); printf("\n"); } if (enc_config.printkey == 2) { ret = 0; goto end; } } } /* Only encrypt/decrypt as we write the file */ if (benc != NULL) wbio = BIO_push(benc, wbio); for (;;) { inl = BIO_read(rbio, (char *) buff, bsize); if (inl <= 0) break; if (BIO_write(wbio, (char *) buff, inl) != inl) { BIO_printf(bio_err, "error writing output file\n"); goto end; } } if (!BIO_flush(wbio)) { BIO_printf(bio_err, "bad decrypt\n"); goto end; } ret = 0; if (enc_config.verbose) { BIO_printf(bio_err, "bytes read :%8ld\n", BIO_number_read(in)); BIO_printf(bio_err, "bytes written:%8ld\n", BIO_number_written(out)); } end: ERR_print_errors(bio_err); free(strbuf); free(buff); BIO_free(in); if (out != NULL) BIO_free_all(out); BIO_free(benc); BIO_free(b64); #ifdef ZLIB BIO_free(bzl); #endif free(pass); return (ret); }
static void test1(const EVP_CIPHER *c,const unsigned char *key,int kn, const unsigned char *iv,int in, const unsigned char *plaintext,int pn, const unsigned char *ciphertext,int cn, int encdec) { EVP_CIPHER_CTX ctx; unsigned char out[4096]; int outl,outl2; printf("Testing cipher %s%s\n",EVP_CIPHER_name(c), (encdec == 1 ? "(encrypt)" : (encdec == 0 ? "(decrypt)" : "(encrypt/decrypt)"))); hexdump(stdout,"Key",key,kn); if(in) hexdump(stdout,"IV",iv,in); hexdump(stdout,"Plaintext",plaintext,pn); hexdump(stdout,"Ciphertext",ciphertext,cn); if(kn != c->key_len) { fprintf(stderr,"Key length doesn't match, got %d expected %d\n",kn, c->key_len); test1_exit(5); } EVP_CIPHER_CTX_init(&ctx); if (encdec != 0) { if(!EVP_EncryptInit_ex(&ctx,c,NULL,key,iv)) { fprintf(stderr,"EncryptInit failed\n"); ERR_print_errors_fp(stderr); test1_exit(10); } EVP_CIPHER_CTX_set_padding(&ctx,0); if(!EVP_EncryptUpdate(&ctx,out,&outl,plaintext,pn)) { fprintf(stderr,"Encrypt failed\n"); ERR_print_errors_fp(stderr); test1_exit(6); } if(!EVP_EncryptFinal_ex(&ctx,out+outl,&outl2)) { fprintf(stderr,"EncryptFinal failed\n"); ERR_print_errors_fp(stderr); test1_exit(7); } if(outl+outl2 != cn) { fprintf(stderr,"Ciphertext length mismatch got %d expected %d\n", outl+outl2,cn); test1_exit(8); } if(memcmp(out,ciphertext,cn)) { fprintf(stderr,"Ciphertext mismatch\n"); hexdump(stderr,"Got",out,cn); hexdump(stderr,"Expected",ciphertext,cn); test1_exit(9); } } if (encdec <= 0) { if(!EVP_DecryptInit_ex(&ctx,c,NULL,key,iv)) { fprintf(stderr,"DecryptInit failed\n"); ERR_print_errors_fp(stderr); test1_exit(11); } EVP_CIPHER_CTX_set_padding(&ctx,0); if(!EVP_DecryptUpdate(&ctx,out,&outl,ciphertext,cn)) { fprintf(stderr,"Decrypt failed\n"); ERR_print_errors_fp(stderr); test1_exit(6); } if(!EVP_DecryptFinal_ex(&ctx,out+outl,&outl2)) { fprintf(stderr,"DecryptFinal failed\n"); ERR_print_errors_fp(stderr); test1_exit(7); } if(outl+outl2 != cn) { fprintf(stderr,"Plaintext length mismatch got %d expected %d\n", outl+outl2,cn); test1_exit(8); } if(memcmp(out,plaintext,cn)) { fprintf(stderr,"Plaintext mismatch\n"); hexdump(stderr,"Got",out,cn); hexdump(stderr,"Expected",plaintext,cn); test1_exit(9); } } EVP_CIPHER_CTX_cleanup(&ctx); printf("\n"); }
int EVP_CipherInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher, ENGINE *impl, const unsigned char *key, const unsigned char *iv, int enc) { if (enc == -1) enc = ctx->encrypt; else { if (enc) enc = 1; ctx->encrypt = enc; } #ifdef OPENSSL_NO_FIPS if(FIPS_selftest_failed()) { FIPSerr(FIPS_F_EVP_CIPHERINIT_EX,FIPS_R_FIPS_SELFTEST_FAILED); ctx->cipher = &bad_cipher; return 0; } #endif #ifndef OPENSSL_NO_ENGINE /* Whether it's nice or not, "Inits" can be used on "Final"'d contexts * so this context may already have an ENGINE! Try to avoid releasing * the previous handle, re-querying for an ENGINE, and having a * reinitialisation, when it may all be unecessary. */ if (ctx->engine && ctx->cipher && (!cipher || (cipher && (cipher->nid == ctx->cipher->nid)))) goto skip_to_init; #endif if (cipher) { /* Ensure a context left lying around from last time is cleared * (the previous check attempted to avoid this if the same * ENGINE and EVP_CIPHER could be used). */ EVP_CIPHER_CTX_cleanup(ctx); /* Restore encrypt field: it is zeroed by cleanup */ ctx->encrypt = enc; #ifndef OPENSSL_NO_ENGINE if (!do_evp_enc_engine(ctx, &cipher, impl)) return 0; #endif ctx->cipher=cipher; if (ctx->cipher->ctx_size) { ctx->cipher_data=OPENSSL_malloc(ctx->cipher->ctx_size); if (!ctx->cipher_data) { EVPerr(EVP_F_EVP_CIPHERINIT_EX, ERR_R_MALLOC_FAILURE); return 0; } } else { ctx->cipher_data = NULL; } ctx->key_len = cipher->key_len; ctx->flags = 0; if(ctx->cipher->flags & EVP_CIPH_CTRL_INIT) { if(!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_INIT, 0, NULL)) { EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_INITIALIZATION_ERROR); return 0; } } } else if(!ctx->cipher) { EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_NO_CIPHER_SET); return 0; } #ifndef OPENSSL_NO_ENGINE skip_to_init: #endif /* we assume block size is a power of 2 in *cryptUpdate */ OPENSSL_assert(ctx->cipher->block_size == 1 || ctx->cipher->block_size == 8 || ctx->cipher->block_size == 16); if(!(EVP_CIPHER_CTX_flags(ctx) & EVP_CIPH_CUSTOM_IV)) { switch(EVP_CIPHER_CTX_mode(ctx)) { case EVP_CIPH_STREAM_CIPHER: case EVP_CIPH_ECB_MODE: break; case EVP_CIPH_CFB_MODE: case EVP_CIPH_OFB_MODE: ctx->num = 0; case EVP_CIPH_CBC_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)); break; default: return 0; break; } } #ifdef OPENSSL_FIPS /* After 'key' is set no further parameters changes are permissible. * So only check for non FIPS enabling at this point. */ if (key && FIPS_mode()) { if (!(ctx->cipher->flags & EVP_CIPH_FLAG_FIPS) & !(ctx->flags & EVP_CIPH_FLAG_NON_FIPS_ALLOW)) { EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_DISABLED_FOR_FIPS); #if 0 ERR_add_error_data(2, "cipher=", EVP_CIPHER_name(ctx->cipher)); #endif ctx->cipher = &bad_cipher; return 0; } } #endif if(key || (ctx->cipher->flags & EVP_CIPH_ALWAYS_CALL_INIT)) { if(!ctx->cipher->init(ctx,key,iv,enc)) return 0; } ctx->buf_len=0; ctx->final_used=0; ctx->block_mask=ctx->cipher->block_size-1; return 1; }
int MAIN(int argc, char **argv) { static const char magic[]="Salted__"; char mbuf[sizeof magic-1]; char *strbuf=NULL; unsigned char *buff=NULL,*bufsize=NULL; int bsize=BSIZE,verbose=0; int ret=1,inl; int nopad = 0; unsigned char key[EVP_MAX_KEY_LENGTH],iv[EVP_MAX_IV_LENGTH]; unsigned char salt[PKCS5_SALT_LEN]; char *str=NULL, *passarg = NULL, *pass = NULL; char *hkey=NULL,*hiv=NULL,*hsalt = NULL; char *md=NULL; int enc=1,printkey=0,i,base64=0; #ifdef ZLIB int do_zlib=0; BIO *bzl = NULL; #endif int debug=0,olb64=0,nosalt=0; const EVP_CIPHER *cipher=NULL,*c; EVP_CIPHER_CTX *ctx = NULL; char *inf=NULL,*outf=NULL; BIO *in=NULL,*out=NULL,*b64=NULL,*benc=NULL,*rbio=NULL,*wbio=NULL; #define PROG_NAME_SIZE 39 char pname[PROG_NAME_SIZE+1]; #ifndef OPENSSL_NO_ENGINE char *engine = NULL; #endif const EVP_MD *dgst=NULL; int non_fips_allow = 0; apps_startup(); if (bio_err == NULL) if ((bio_err=BIO_new(BIO_s_file())) != NULL) BIO_set_fp(bio_err,stderr,BIO_NOCLOSE|BIO_FP_TEXT); if (!load_config(bio_err, NULL)) goto end; /* first check the program name */ program_name(argv[0],pname,sizeof pname); if (strcmp(pname,"base64") == 0) base64=1; #ifdef ZLIB if (strcmp(pname,"zlib") == 0) do_zlib=1; #endif cipher=EVP_get_cipherbyname(pname); #ifdef ZLIB if (!do_zlib && !base64 && (cipher == NULL) && (strcmp(pname,"enc") != 0)) #else if (!base64 && (cipher == NULL) && (strcmp(pname,"enc") != 0)) #endif { BIO_printf(bio_err,"%s is an unknown cipher\n",pname); goto bad; } argc--; argv++; while (argc >= 1) { if (strcmp(*argv,"-e") == 0) enc=1; else if (strcmp(*argv,"-in") == 0) { if (--argc < 1) goto bad; inf= *(++argv); } else if (strcmp(*argv,"-out") == 0) { if (--argc < 1) goto bad; outf= *(++argv); } else if (strcmp(*argv,"-pass") == 0) { if (--argc < 1) goto bad; passarg= *(++argv); } #ifndef OPENSSL_NO_ENGINE else if (strcmp(*argv,"-engine") == 0) { if (--argc < 1) goto bad; engine= *(++argv); } #endif else if (strcmp(*argv,"-d") == 0) enc=0; else if (strcmp(*argv,"-p") == 0) printkey=1; else if (strcmp(*argv,"-v") == 0) verbose=1; else if (strcmp(*argv,"-nopad") == 0) nopad=1; else if (strcmp(*argv,"-salt") == 0) nosalt=0; else if (strcmp(*argv,"-nosalt") == 0) nosalt=1; else if (strcmp(*argv,"-debug") == 0) debug=1; else if (strcmp(*argv,"-P") == 0) printkey=2; else if (strcmp(*argv,"-A") == 0) olb64=1; else if (strcmp(*argv,"-a") == 0) base64=1; else if (strcmp(*argv,"-base64") == 0) base64=1; #ifdef ZLIB else if (strcmp(*argv,"-z") == 0) do_zlib=1; #endif else if (strcmp(*argv,"-bufsize") == 0) { if (--argc < 1) goto bad; bufsize=(unsigned char *)*(++argv); } else if (strcmp(*argv,"-k") == 0) { if (--argc < 1) goto bad; str= *(++argv); } else if (strcmp(*argv,"-kfile") == 0) { static char buf[128]; FILE *infile; char *file; if (--argc < 1) goto bad; file= *(++argv); infile=fopen(file,"r"); if (infile == NULL) { BIO_printf(bio_err,"unable to read key from '%s'\n", file); goto bad; } buf[0]='\0'; if (!fgets(buf,sizeof buf,infile)) { BIO_printf(bio_err,"unable to read key from '%s'\n", file); goto bad; } fclose(infile); i=strlen(buf); if ((i > 0) && ((buf[i-1] == '\n') || (buf[i-1] == '\r'))) buf[--i]='\0'; if ((i > 0) && ((buf[i-1] == '\n') || (buf[i-1] == '\r'))) buf[--i]='\0'; if (i < 1) { BIO_printf(bio_err,"zero length password\n"); goto bad; } str=buf; } else if (strcmp(*argv,"-K") == 0) { if (--argc < 1) goto bad; hkey= *(++argv); } else if (strcmp(*argv,"-S") == 0) { if (--argc < 1) goto bad; hsalt= *(++argv); } else if (strcmp(*argv,"-iv") == 0) { if (--argc < 1) goto bad; hiv= *(++argv); } else if (strcmp(*argv,"-md") == 0) { if (--argc < 1) goto bad; md= *(++argv); } else if (strcmp(*argv,"-non-fips-allow") == 0) non_fips_allow = 1; else if ((argv[0][0] == '-') && ((c=EVP_get_cipherbyname(&(argv[0][1]))) != NULL)) { cipher=c; } else if (strcmp(*argv,"-none") == 0) cipher=NULL; else { BIO_printf(bio_err,"unknown option '%s'\n",*argv); bad: BIO_printf(bio_err,"options are\n"); BIO_printf(bio_err,"%-14s input file\n","-in <file>"); BIO_printf(bio_err,"%-14s output file\n","-out <file>"); BIO_printf(bio_err,"%-14s pass phrase source\n","-pass <arg>"); BIO_printf(bio_err,"%-14s encrypt\n","-e"); BIO_printf(bio_err,"%-14s decrypt\n","-d"); BIO_printf(bio_err,"%-14s base64 encode/decode, depending on encryption flag\n","-a/-base64"); BIO_printf(bio_err,"%-14s passphrase is the next argument\n","-k"); BIO_printf(bio_err,"%-14s passphrase is the first line of the file argument\n","-kfile"); BIO_printf(bio_err,"%-14s the next argument is the md to use to create a key\n","-md"); BIO_printf(bio_err,"%-14s from a passphrase. One of md2, md5, sha or sha1\n",""); BIO_printf(bio_err,"%-14s salt in hex is the next argument\n","-S"); BIO_printf(bio_err,"%-14s key/iv in hex is the next argument\n","-K/-iv"); BIO_printf(bio_err,"%-14s print the iv/key (then exit if -P)\n","-[pP]"); BIO_printf(bio_err,"%-14s buffer size\n","-bufsize <n>"); BIO_printf(bio_err,"%-14s disable standard block padding\n","-nopad"); #ifndef OPENSSL_NO_ENGINE BIO_printf(bio_err,"%-14s use engine e, possibly a hardware device.\n","-engine e"); #endif BIO_printf(bio_err,"Cipher Types\n"); OBJ_NAME_do_all_sorted(OBJ_NAME_TYPE_CIPHER_METH, show_ciphers, bio_err); BIO_printf(bio_err,"\n"); goto end; } argc--; argv++; } #ifndef OPENSSL_NO_ENGINE setup_engine(bio_err, engine, 0); #endif if (md && (dgst=EVP_get_digestbyname(md)) == NULL) { BIO_printf(bio_err,"%s is an unsupported message digest type\n",md); goto end; } if (dgst == NULL) { dgst = EVP_md5(); } if (bufsize != NULL) { unsigned long n; for (n=0; *bufsize; bufsize++) { i= *bufsize; if ((i <= '9') && (i >= '0')) n=n*10+i-'0'; else if (i == 'k') { n*=1024; bufsize++; break; } } if (*bufsize != '\0') { BIO_printf(bio_err,"invalid 'bufsize' specified.\n"); goto end; } /* It must be large enough for a base64 encoded line */ if (base64 && n < 80) n=80; bsize=(int)n; if (verbose) BIO_printf(bio_err,"bufsize=%d\n",bsize); } strbuf=OPENSSL_malloc(SIZE); buff=(unsigned char *)OPENSSL_malloc(EVP_ENCODE_LENGTH(bsize)); if ((buff == NULL) || (strbuf == NULL)) { BIO_printf(bio_err,"OPENSSL_malloc failure %ld\n",(long)EVP_ENCODE_LENGTH(bsize)); goto end; } in=BIO_new(BIO_s_file()); out=BIO_new(BIO_s_file()); if ((in == NULL) || (out == NULL)) { ERR_print_errors(bio_err); goto end; } if (debug) { BIO_set_callback(in,BIO_debug_callback); BIO_set_callback(out,BIO_debug_callback); BIO_set_callback_arg(in,(char *)bio_err); BIO_set_callback_arg(out,(char *)bio_err); } if (inf == NULL) { #ifndef OPENSSL_NO_SETVBUF_IONBF if (bufsize != NULL) setvbuf(stdin, (char *)NULL, _IONBF, 0); #endif /* ndef OPENSSL_NO_SETVBUF_IONBF */ BIO_set_fp(in,stdin,BIO_NOCLOSE); } else { if (BIO_read_filename(in,inf) <= 0) { perror(inf); goto end; } } if(!str && passarg) { if(!app_passwd(bio_err, passarg, NULL, &pass, NULL)) { BIO_printf(bio_err, "Error getting password\n"); goto end; } str = pass; } if ((str == NULL) && (cipher != NULL) && (hkey == NULL)) { for (;;) { char buf[200]; BIO_snprintf(buf,sizeof buf,"enter %s %s password:"******"encryption":"decryption"); strbuf[0]='\0'; i=EVP_read_pw_string((char *)strbuf,SIZE,buf,enc); if (i == 0) { if (strbuf[0] == '\0') { ret=1; goto end; } str=strbuf; break; } if (i < 0) { BIO_printf(bio_err,"bad password read\n"); goto end; } } } if (outf == NULL) { BIO_set_fp(out,stdout,BIO_NOCLOSE); #ifndef OPENSSL_NO_SETVBUF_IONBF if (bufsize != NULL) setvbuf(stdout, (char *)NULL, _IONBF, 0); #endif /* ndef OPENSSL_NO_SETVBUF_IONBF */ #ifdef OPENSSL_SYS_VMS { BIO *tmpbio = BIO_new(BIO_f_linebuffer()); out = BIO_push(tmpbio, out); } #endif } else { if (BIO_write_filename(out,outf) <= 0) { perror(outf); goto end; } } rbio=in; wbio=out; #ifdef ZLIB if (do_zlib) { if ((bzl=BIO_new(BIO_f_zlib())) == NULL) goto end; if (enc) wbio=BIO_push(bzl,wbio); else rbio=BIO_push(bzl,rbio); } #endif if (base64) { if ((b64=BIO_new(BIO_f_base64())) == NULL) goto end; if (debug) { BIO_set_callback(b64,BIO_debug_callback); BIO_set_callback_arg(b64,(char *)bio_err); } if (olb64) BIO_set_flags(b64,BIO_FLAGS_BASE64_NO_NL); if (enc) wbio=BIO_push(b64,wbio); else rbio=BIO_push(b64,rbio); } if (cipher != NULL) { /* Note that str is NULL if a key was passed on the command * line, so we get no salt in that case. Is this a bug? */ if (str != NULL) { /* Salt handling: if encrypting generate a salt and * write to output BIO. If decrypting read salt from * input BIO. */ unsigned char *sptr; if(nosalt) sptr = NULL; else { if(enc) { if(hsalt) { if(!set_hex(hsalt,salt,sizeof salt)) { BIO_printf(bio_err, "invalid hex salt value\n"); goto end; } } else if (RAND_pseudo_bytes(salt, sizeof salt) < 0) goto end; /* If -P option then don't bother writing */ if((printkey != 2) && (BIO_write(wbio,magic, sizeof magic-1) != sizeof magic-1 || BIO_write(wbio, (char *)salt, sizeof salt) != sizeof salt)) { BIO_printf(bio_err,"error writing output file\n"); goto end; } } else if(BIO_read(rbio,mbuf,sizeof mbuf) != sizeof mbuf || BIO_read(rbio, (unsigned char *)salt, sizeof salt) != sizeof salt) { BIO_printf(bio_err,"error reading input file\n"); goto end; } else if(memcmp(mbuf,magic,sizeof magic-1)) { BIO_printf(bio_err,"bad magic number\n"); goto end; } sptr = salt; } EVP_BytesToKey(cipher,dgst,sptr, (unsigned char *)str, strlen(str),1,key,iv); /* zero the complete buffer or the string * passed from the command line * bug picked up by * Larry J. Hughes Jr. <*****@*****.**> */ if (str == strbuf) OPENSSL_cleanse(str,SIZE); else OPENSSL_cleanse(str,strlen(str)); } if ((hiv != NULL) && !set_hex(hiv,iv,sizeof iv)) { BIO_printf(bio_err,"invalid hex iv value\n"); goto end; } if ((hiv == NULL) && (str == NULL) && EVP_CIPHER_iv_length(cipher) != 0) { /* No IV was explicitly set and no IV was generated * during EVP_BytesToKey. Hence the IV is undefined, * making correct decryption impossible. */ BIO_printf(bio_err, "iv undefined\n"); goto end; } if ((hkey != NULL) && !set_hex(hkey,key,sizeof key)) { BIO_printf(bio_err,"invalid hex key value\n"); goto end; } if ((benc=BIO_new(BIO_f_cipher())) == NULL) goto end; /* Since we may be changing parameters work on the encryption * context rather than calling BIO_set_cipher(). */ BIO_get_cipher_ctx(benc, &ctx); if (non_fips_allow) EVP_CIPHER_CTX_set_flags(ctx, EVP_CIPH_FLAG_NON_FIPS_ALLOW); if (!EVP_CipherInit_ex(ctx, cipher, NULL, NULL, NULL, enc)) { BIO_printf(bio_err, "Error setting cipher %s\n", EVP_CIPHER_name(cipher)); ERR_print_errors(bio_err); goto end; } if (nopad) EVP_CIPHER_CTX_set_padding(ctx, 0); if (!EVP_CipherInit_ex(ctx, NULL, NULL, key, iv, enc)) { BIO_printf(bio_err, "Error setting cipher %s\n", EVP_CIPHER_name(cipher)); ERR_print_errors(bio_err); goto end; } if (debug) { BIO_set_callback(benc,BIO_debug_callback); BIO_set_callback_arg(benc,(char *)bio_err); } if (printkey) { if (!nosalt) { printf("salt="); for (i=0; i<(int)sizeof(salt); i++) printf("%02X",salt[i]); printf("\n"); } if (cipher->key_len > 0) { printf("key="); for (i=0; i<cipher->key_len; i++) printf("%02X",key[i]); printf("\n"); } if (cipher->iv_len > 0) { printf("iv ="); for (i=0; i<cipher->iv_len; i++) printf("%02X",iv[i]); printf("\n"); } if (printkey == 2) { ret=0; goto end; } } } /* Only encrypt/decrypt as we write the file */ if (benc != NULL) wbio=BIO_push(benc,wbio); for (;;) { inl=BIO_read(rbio,(char *)buff,bsize); if (inl <= 0) break; if (BIO_write(wbio,(char *)buff,inl) != inl) { BIO_printf(bio_err,"error writing output file\n"); goto end; } } if (!BIO_flush(wbio)) { BIO_printf(bio_err,"bad decrypt\n"); goto end; } ret=0; if (verbose) { BIO_printf(bio_err,"bytes read :%8ld\n",BIO_number_read(in)); BIO_printf(bio_err,"bytes written:%8ld\n",BIO_number_written(out)); } end: ERR_print_errors(bio_err); if (strbuf != NULL) OPENSSL_free(strbuf); if (buff != NULL) OPENSSL_free(buff); if (in != NULL) BIO_free(in); if (out != NULL) BIO_free_all(out); if (benc != NULL) BIO_free(benc); if (b64 != NULL) BIO_free(b64); #ifdef ZLIB if (bzl != NULL) BIO_free(bzl); #endif if(pass) OPENSSL_free(pass); apps_shutdown(); OPENSSL_EXIT(ret); }
int enc_main(int argc, char **argv) { static char buf[128]; static const char magic[] = "Salted__"; BIO *in = NULL, *out = NULL, *b64 = NULL, *benc = NULL, *rbio = NULL, *wbio = NULL; EVP_CIPHER_CTX *ctx = NULL; const EVP_CIPHER *cipher = NULL, *c; const EVP_MD *dgst = NULL; char *hkey = NULL, *hiv = NULL, *hsalt = NULL, *p; char *infile = NULL, *outfile = NULL, *prog; char *str = NULL, *passarg = NULL, *pass = NULL, *strbuf = NULL; char mbuf[sizeof magic - 1]; OPTION_CHOICE o; int bsize = BSIZE, verbose = 0, debug = 0, olb64 = 0, nosalt = 0; int enc = 1, printkey = 0, i, k; int base64 = 0, informat = FORMAT_BINARY, outformat = FORMAT_BINARY; int ret = 1, inl, nopad = 0, non_fips_allow = 0; unsigned char key[EVP_MAX_KEY_LENGTH], iv[EVP_MAX_IV_LENGTH]; unsigned char *buff = NULL, salt[PKCS5_SALT_LEN]; unsigned long n; #ifdef ZLIB int do_zlib = 0; BIO *bzl = NULL; #endif /* first check the program name */ prog = opt_progname(argv[0]); if (strcmp(prog, "base64") == 0) base64 = 1; #ifdef ZLIB else if (strcmp(prog, "zlib") == 0) do_zlib = 1; #endif else { cipher = EVP_get_cipherbyname(prog); if (cipher == NULL && strcmp(prog, "enc") != 0) { BIO_printf(bio_err, "%s is not a known cipher\n", prog); goto end; } } prog = opt_init(argc, argv, enc_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_EOF: case OPT_ERR: opthelp: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; case OPT_HELP: opt_help(enc_options); ret = 0; BIO_printf(bio_err, "Cipher Types\n"); OBJ_NAME_do_all_sorted(OBJ_NAME_TYPE_CIPHER_METH, show_ciphers, bio_err); BIO_printf(bio_err, "\n"); goto end; case OPT_E: enc = 1; break; case OPT_IN: infile = opt_arg(); break; case OPT_OUT: outfile = opt_arg(); break; case OPT_PASS: passarg = opt_arg(); break; case OPT_ENGINE: (void)setup_engine(opt_arg(), 0); break; case OPT_D: enc = 0; break; case OPT_P: printkey = 1; break; case OPT_V: verbose = 1; break; case OPT_NOPAD: nopad = 1; break; case OPT_SALT: nosalt = 0; break; case OPT_NOSALT: nosalt = 1; break; case OPT_DEBUG: debug = 1; break; case OPT_UPPER_P: printkey = 2; break; case OPT_UPPER_A: olb64 = 1; break; case OPT_A: base64 = 1; break; case OPT_Z: #ifdef ZLIB do_zlib = 1; #endif break; case OPT_BUFSIZE: p = opt_arg(); i = (int)strlen(p) - 1; k = i >= 1 && p[i] == 'k'; if (k) p[i] = '\0'; if (!opt_ulong(opt_arg(), &n)) goto opthelp; if (k) n *= 1024; bsize = (int)n; break; case OPT_K: str = opt_arg(); break; case OPT_KFILE: in = bio_open_default(opt_arg(), 'r', FORMAT_TEXT); if (in == NULL) goto opthelp; i = BIO_gets(in, buf, sizeof buf); BIO_free(in); in = NULL; if (i <= 0) { BIO_printf(bio_err, "%s Can't read key from %s\n", prog, opt_arg()); goto opthelp; } while (--i > 0 && (buf[i] == '\r' || buf[i] == '\n')) buf[i] = '\0'; if (i <= 0) { BIO_printf(bio_err, "%s: zero length password\n", prog); goto opthelp; } str = buf; break; case OPT_UPPER_K: hkey = opt_arg(); break; case OPT_UPPER_S: hsalt = opt_arg(); break; case OPT_IV: hiv = opt_arg(); break; case OPT_MD: if (!opt_md(opt_arg(), &dgst)) goto opthelp; break; case OPT_NON_FIPS_ALLOW: non_fips_allow = 1; break; case OPT_CIPHER: if (!opt_cipher(opt_unknown(), &c)) goto opthelp; cipher = c; break; case OPT_NONE: cipher = NULL; break; } } argc = opt_num_rest(); argv = opt_rest(); if (cipher && EVP_CIPHER_flags(cipher) & EVP_CIPH_FLAG_AEAD_CIPHER) { BIO_printf(bio_err, "%s: AEAD ciphers not supported\n", prog); goto end; } if (cipher && (EVP_CIPHER_mode(cipher) == EVP_CIPH_XTS_MODE)) { BIO_printf(bio_err, "%s XTS ciphers not supported\n", prog); goto end; } if (dgst == NULL) dgst = EVP_sha256(); /* It must be large enough for a base64 encoded line */ if (base64 && bsize < 80) bsize = 80; if (verbose) BIO_printf(bio_err, "bufsize=%d\n", bsize); if (base64) { if (enc) outformat = FORMAT_BASE64; else informat = FORMAT_BASE64; } strbuf = app_malloc(SIZE, "strbuf"); buff = app_malloc(EVP_ENCODE_LENGTH(bsize), "evp buffer"); if (debug) { BIO_set_callback(in, BIO_debug_callback); BIO_set_callback(out, BIO_debug_callback); BIO_set_callback_arg(in, (char *)bio_err); BIO_set_callback_arg(out, (char *)bio_err); } if (infile == NULL) { unbuffer(stdin); in = dup_bio_in(informat); } else in = bio_open_default(infile, 'r', informat); if (in == NULL) goto end; if (!str && passarg) { if (!app_passwd(passarg, NULL, &pass, NULL)) { BIO_printf(bio_err, "Error getting password\n"); goto end; } str = pass; } if ((str == NULL) && (cipher != NULL) && (hkey == NULL)) { for (;;) { char prompt[200]; BIO_snprintf(prompt, sizeof prompt, "enter %s %s password:"******"encryption" : "decryption"); strbuf[0] = '\0'; i = EVP_read_pw_string((char *)strbuf, SIZE, prompt, enc); if (i == 0) { if (strbuf[0] == '\0') { ret = 1; goto end; } str = strbuf; break; } if (i < 0) { BIO_printf(bio_err, "bad password read\n"); goto end; } } } out = bio_open_default(outfile, 'w', outformat); if (out == NULL) goto end; rbio = in; wbio = out; #ifdef ZLIB if (do_zlib) { if ((bzl = BIO_new(BIO_f_zlib())) == NULL) goto end; if (enc) wbio = BIO_push(bzl, wbio); else rbio = BIO_push(bzl, rbio); } #endif if (base64) { if ((b64 = BIO_new(BIO_f_base64())) == NULL) goto end; if (debug) { BIO_set_callback(b64, BIO_debug_callback); BIO_set_callback_arg(b64, (char *)bio_err); } if (olb64) BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL); if (enc) wbio = BIO_push(b64, wbio); else rbio = BIO_push(b64, rbio); } if (cipher != NULL) { /* * Note that str is NULL if a key was passed on the command line, so * we get no salt in that case. Is this a bug? */ if (str != NULL) { /* * Salt handling: if encrypting generate a salt and write to * output BIO. If decrypting read salt from input BIO. */ unsigned char *sptr; if (nosalt) sptr = NULL; else { if (enc) { if (hsalt) { if (!set_hex(hsalt, salt, sizeof salt)) { BIO_printf(bio_err, "invalid hex salt value\n"); goto end; } } else if (RAND_bytes(salt, sizeof salt) <= 0) goto end; /* * If -P option then don't bother writing */ if ((printkey != 2) && (BIO_write(wbio, magic, sizeof magic - 1) != sizeof magic - 1 || BIO_write(wbio, (char *)salt, sizeof salt) != sizeof salt)) { BIO_printf(bio_err, "error writing output file\n"); goto end; } } else if (BIO_read(rbio, mbuf, sizeof mbuf) != sizeof mbuf || BIO_read(rbio, (unsigned char *)salt, sizeof salt) != sizeof salt) { BIO_printf(bio_err, "error reading input file\n"); goto end; } else if (memcmp(mbuf, magic, sizeof magic - 1)) { BIO_printf(bio_err, "bad magic number\n"); goto end; } sptr = salt; } if (!EVP_BytesToKey(cipher, dgst, sptr, (unsigned char *)str, strlen(str), 1, key, iv)) { BIO_printf(bio_err, "EVP_BytesToKey failed\n"); goto end; } /* * zero the complete buffer or the string passed from the command * line bug picked up by Larry J. Hughes Jr. <*****@*****.**> */ if (str == strbuf) OPENSSL_cleanse(str, SIZE); else OPENSSL_cleanse(str, strlen(str)); } if (hiv != NULL) { int siz = EVP_CIPHER_iv_length(cipher); if (siz == 0) { BIO_printf(bio_err, "warning: iv not use by this cipher\n"); } else if (!set_hex(hiv, iv, sizeof iv)) { BIO_printf(bio_err, "invalid hex iv value\n"); goto end; } } if ((hiv == NULL) && (str == NULL) && EVP_CIPHER_iv_length(cipher) != 0) { /* * No IV was explicitly set and no IV was generated during * EVP_BytesToKey. Hence the IV is undefined, making correct * decryption impossible. */ BIO_printf(bio_err, "iv undefined\n"); goto end; } if ((hkey != NULL) && !set_hex(hkey, key, EVP_CIPHER_key_length(cipher))) { BIO_printf(bio_err, "invalid hex key value\n"); goto end; } if ((benc = BIO_new(BIO_f_cipher())) == NULL) goto end; /* * Since we may be changing parameters work on the encryption context * rather than calling BIO_set_cipher(). */ BIO_get_cipher_ctx(benc, &ctx); if (non_fips_allow) EVP_CIPHER_CTX_set_flags(ctx, EVP_CIPH_FLAG_NON_FIPS_ALLOW); if (!EVP_CipherInit_ex(ctx, cipher, NULL, NULL, NULL, enc)) { BIO_printf(bio_err, "Error setting cipher %s\n", EVP_CIPHER_name(cipher)); ERR_print_errors(bio_err); goto end; } if (nopad) EVP_CIPHER_CTX_set_padding(ctx, 0); if (!EVP_CipherInit_ex(ctx, NULL, NULL, key, iv, enc)) { BIO_printf(bio_err, "Error setting cipher %s\n", EVP_CIPHER_name(cipher)); ERR_print_errors(bio_err); goto end; } if (debug) { BIO_set_callback(benc, BIO_debug_callback); BIO_set_callback_arg(benc, (char *)bio_err); } if (printkey) { if (!nosalt) { printf("salt="); for (i = 0; i < (int)sizeof(salt); i++) printf("%02X", salt[i]); printf("\n"); } if (cipher->key_len > 0) { printf("key="); for (i = 0; i < cipher->key_len; i++) printf("%02X", key[i]); printf("\n"); } if (cipher->iv_len > 0) { printf("iv ="); for (i = 0; i < cipher->iv_len; i++) printf("%02X", iv[i]); printf("\n"); } if (printkey == 2) { ret = 0; goto end; } } } /* Only encrypt/decrypt as we write the file */ if (benc != NULL) wbio = BIO_push(benc, wbio); for (;;) { inl = BIO_read(rbio, (char *)buff, bsize); if (inl <= 0) break; if (BIO_write(wbio, (char *)buff, inl) != inl) { BIO_printf(bio_err, "error writing output file\n"); goto end; } } if (!BIO_flush(wbio)) { BIO_printf(bio_err, "bad decrypt\n"); goto end; } ret = 0; if (verbose) { BIO_printf(bio_err, "bytes read :%8"PRIu64"\n", BIO_number_read(in)); BIO_printf(bio_err, "bytes written:%8"PRIu64"\n", BIO_number_written(out)); } end: ERR_print_errors(bio_err); OPENSSL_free(strbuf); OPENSSL_free(buff); BIO_free(in); BIO_free_all(out); BIO_free(benc); BIO_free(b64); #ifdef ZLIB BIO_free(bzl); #endif OPENSSL_free(pass); return (ret); }
static const char* sqlcipher_openssl_get_cipher(void *ctx) { return EVP_CIPHER_name(((openssl_ctx *)ctx)->evp_cipher); }
static int ssl_decrypt_record( dssl_decoder_stack* stack, u_char* data, uint32_t len, u_char** out, uint32_t* out_len, int *buffer_aquired ) { u_char* buf = NULL; uint32_t buf_len = len; int rc = DSSL_RC_OK; int block_size; const EVP_CIPHER* c = NULL; _ASSERT( stack ); _ASSERT( stack->sess ); _ASSERT( stack->cipher ); rc = ssls_get_decrypt_buffer( stack->sess, &buf, buf_len ); if( rc != DSSL_RC_OK ) return rc; *buffer_aquired = 1; c = EVP_CIPHER_CTX_cipher( stack->cipher ); block_size = EVP_CIPHER_block_size( c ); DEBUG_TRACE3( "using cipher %s (mode=%u, block=%u)\n", EVP_CIPHER_name(c), stack->sess->cipher_mode, block_size ); if( block_size != 1 ) { if( len == 0 || (len % block_size) != 0 ) { return NM_ERROR( DSSL_E_SSL_DECRYPTION_ERROR ); } } DEBUG_TRACE_BUF("encrypted", data, len); if ( EVP_CIPH_GCM_MODE == stack->sess->cipher_mode || EVP_CIPH_CCM_MODE == stack->sess->cipher_mode ) { if ( len < EVP_GCM_TLS_EXPLICIT_IV_LEN ) { return NM_ERROR( DSSL_E_SSL_DECRYPTION_ERROR ); } if ( EVP_CIPH_GCM_MODE == stack->sess->cipher_mode ) { /* set 'explicit_nonce' part from message bytes */ rc = EVP_CIPHER_CTX_ctrl(stack->cipher, EVP_CTRL_GCM_SET_IV_INV, EVP_GCM_TLS_EXPLICIT_IV_LEN, data); } else { /* 4 bytes write_iv, 8 bytes explicit_nonce, 4 bytes counter */ u_char ccm_nonce[EVP_GCM_TLS_TAG_LEN] = { 0 }; rc = EVP_CIPHER_CTX_ctrl(stack->cipher, EVP_CTRL_CCM_GET_TAG, sizeof(ccm_nonce), ccm_nonce); if( rc != DSSL_RC_OK ) return rc; /* overwrite exlicit_nonce part with packet data */ memcpy(ccm_nonce + 1 + EVP_GCM_TLS_FIXED_IV_LEN, data, EVP_GCM_TLS_EXPLICIT_IV_LEN); rc = EVP_CIPHER_CTX_ctrl(stack->cipher, EVP_CTRL_CCM_SET_TAG, sizeof(ccm_nonce), ccm_nonce); if( rc != DSSL_RC_OK ) return rc; } data += EVP_GCM_TLS_EXPLICIT_IV_LEN; len -= EVP_GCM_TLS_EXPLICIT_IV_LEN; } rc = EVP_Cipher(stack->cipher, buf, data, len ); buf_len = len; /* strip the padding */ if( block_size != 1 ) { if( buf[len-1] >= buf_len - 1 ) return NM_ERROR( DSSL_E_SSL_DECRYPTION_ERROR ); buf_len -= buf[len-1] + 1; } DEBUG_TRACE_BUF("decrypted", buf, buf_len); /* ignore auth tag, which is 16 (for CCM/GCM) or 8 (for CCM-8) bytes */ if ( EVP_CIPH_GCM_MODE == stack->sess->cipher_mode || EVP_CIPH_CCM_MODE == stack->sess->cipher_mode ) { if (NULL == stack->sess->dssl_cipher_suite->extra_info) buf_len -= EVP_GCM_TLS_TAG_LEN; else buf_len -= (size_t)stack->sess->dssl_cipher_suite->extra_info; } *out = buf; *out_len = buf_len; return DSSL_RC_OK; }
static void test1(const EVP_CIPHER *c,const unsigned char *key,int kn, const unsigned char *iv,int in, const unsigned char *plaintext,int pn, const unsigned char *ciphertext,int cn, const unsigned char *aad,int an, const unsigned char *tag,int tn, int encdec) { EVP_CIPHER_CTX ctx; unsigned char out[4096]; int outl,outl2,mode; printf("Testing cipher %s%s\n",EVP_CIPHER_name(c), (encdec == 1 ? "(encrypt)" : (encdec == 0 ? "(decrypt)" : "(encrypt/decrypt)"))); hexdump(stdout,"Key",key,kn); if(in) hexdump(stdout,"IV",iv,in); hexdump(stdout,"Plaintext",plaintext,pn); hexdump(stdout,"Ciphertext",ciphertext,cn); if (an) hexdump(stdout,"AAD",aad,an); if (tn) hexdump(stdout,"Tag",tag,tn); mode = EVP_CIPHER_mode(c); if(kn != EVP_CIPHER_key_length(c)) { fprintf(stderr,"Key length doesn't match, got %d expected %lu\n",kn, (unsigned long)EVP_CIPHER_key_length(c)); test1_exit(5); } EVP_CIPHER_CTX_init(&ctx); if (encdec != 0) { if (mode == EVP_CIPH_GCM_MODE) { if(!EVP_EncryptInit_ex(&ctx,c,NULL,NULL,NULL)) { fprintf(stderr,"EncryptInit failed\n"); ERR_print_errors_fp(stderr); test1_exit(10); } if(!EVP_CIPHER_CTX_ctrl(&ctx, EVP_CTRL_GCM_SET_IVLEN, in, NULL)) { fprintf(stderr,"IV length set failed\n"); ERR_print_errors_fp(stderr); test1_exit(11); } if(!EVP_EncryptInit_ex(&ctx,NULL,NULL,key,iv)) { fprintf(stderr,"Key/IV set failed\n"); ERR_print_errors_fp(stderr); test1_exit(12); } if (an && !EVP_EncryptUpdate(&ctx,NULL,&outl,aad,an)) { fprintf(stderr,"AAD set failed\n"); ERR_print_errors_fp(stderr); test1_exit(13); } } else if (mode == EVP_CIPH_CCM_MODE) { if(!EVP_EncryptInit_ex(&ctx,c,NULL,NULL,NULL)) { fprintf(stderr,"EncryptInit failed\n"); ERR_print_errors_fp(stderr); test1_exit(10); } if(!EVP_CIPHER_CTX_ctrl(&ctx, EVP_CTRL_CCM_SET_IVLEN, in, NULL)) { fprintf(stderr,"IV length set failed\n"); ERR_print_errors_fp(stderr); test1_exit(11); } if(!EVP_CIPHER_CTX_ctrl(&ctx, EVP_CTRL_CCM_SET_TAG, tn, NULL)) { fprintf(stderr,"Tag length set failed\n"); ERR_print_errors_fp(stderr); test1_exit(11); } if(!EVP_EncryptInit_ex(&ctx,NULL,NULL,key,iv)) { fprintf(stderr,"Key/IV set failed\n"); ERR_print_errors_fp(stderr); test1_exit(12); } if (!EVP_EncryptUpdate(&ctx,NULL,&outl,NULL,pn)) { fprintf(stderr,"Plaintext length set failed\n"); ERR_print_errors_fp(stderr); test1_exit(12); } if (an && !EVP_EncryptUpdate(&ctx,NULL,&outl,aad,an)) { fprintf(stderr,"AAD set failed\n"); ERR_print_errors_fp(stderr); test1_exit(13); } } else if(!EVP_EncryptInit_ex(&ctx,c,NULL,key,iv)) { fprintf(stderr,"EncryptInit failed\n"); ERR_print_errors_fp(stderr); test1_exit(10); } EVP_CIPHER_CTX_set_padding(&ctx,0); if(!EVP_EncryptUpdate(&ctx,out,&outl,plaintext,pn)) { fprintf(stderr,"Encrypt failed\n"); ERR_print_errors_fp(stderr); test1_exit(6); } if(!EVP_EncryptFinal_ex(&ctx,out+outl,&outl2)) { fprintf(stderr,"EncryptFinal failed\n"); ERR_print_errors_fp(stderr); test1_exit(7); } if(outl+outl2 != cn) { fprintf(stderr,"Ciphertext length mismatch got %d expected %d\n", outl+outl2,cn); test1_exit(8); } if(memcmp(out,ciphertext,cn)) { fprintf(stderr,"Ciphertext mismatch\n"); hexdump(stderr,"Got",out,cn); hexdump(stderr,"Expected",ciphertext,cn); test1_exit(9); } if (mode == EVP_CIPH_GCM_MODE || mode == EVP_CIPH_CCM_MODE) { unsigned char rtag[16]; /* Note: EVP_CTRL_CCM_GET_TAG has same value as * EVP_CTRL_GCM_GET_TAG */ if (!EVP_CIPHER_CTX_ctrl(&ctx, EVP_CTRL_GCM_GET_TAG, tn, rtag)) { fprintf(stderr,"Get tag failed\n"); ERR_print_errors_fp(stderr); test1_exit(14); } if (memcmp(rtag, tag, tn)) { fprintf(stderr,"Tag mismatch\n"); hexdump(stderr,"Got",rtag,tn); hexdump(stderr,"Expected",tag,tn); test1_exit(9); } } } if (encdec <= 0) { if (mode == EVP_CIPH_GCM_MODE) { if(!EVP_DecryptInit_ex(&ctx,c,NULL,NULL,NULL)) { fprintf(stderr,"EncryptInit failed\n"); ERR_print_errors_fp(stderr); test1_exit(10); } if(!EVP_CIPHER_CTX_ctrl(&ctx, EVP_CTRL_GCM_SET_IVLEN, in, NULL)) { fprintf(stderr,"IV length set failed\n"); ERR_print_errors_fp(stderr); test1_exit(11); } if(!EVP_DecryptInit_ex(&ctx,NULL,NULL,key,iv)) { fprintf(stderr,"Key/IV set failed\n"); ERR_print_errors_fp(stderr); test1_exit(12); } if (!EVP_CIPHER_CTX_ctrl(&ctx, EVP_CTRL_GCM_SET_TAG, tn, (void *)tag)) { fprintf(stderr,"Set tag failed\n"); ERR_print_errors_fp(stderr); test1_exit(14); } if (an && !EVP_DecryptUpdate(&ctx,NULL,&outl,aad,an)) { fprintf(stderr,"AAD set failed\n"); ERR_print_errors_fp(stderr); test1_exit(13); } } else if (mode == EVP_CIPH_CCM_MODE) { if(!EVP_DecryptInit_ex(&ctx,c,NULL,NULL,NULL)) { fprintf(stderr,"DecryptInit failed\n"); ERR_print_errors_fp(stderr); test1_exit(10); } if(!EVP_CIPHER_CTX_ctrl(&ctx, EVP_CTRL_CCM_SET_IVLEN, in, NULL)) { fprintf(stderr,"IV length set failed\n"); ERR_print_errors_fp(stderr); test1_exit(11); } if(!EVP_CIPHER_CTX_ctrl(&ctx, EVP_CTRL_CCM_SET_TAG, tn, (void *)tag)) { fprintf(stderr,"Tag length set failed\n"); ERR_print_errors_fp(stderr); test1_exit(11); } if(!EVP_DecryptInit_ex(&ctx,NULL,NULL,key,iv)) { fprintf(stderr,"Key/Nonce set failed\n"); ERR_print_errors_fp(stderr); test1_exit(12); } if (!EVP_DecryptUpdate(&ctx,NULL,&outl,NULL,pn)) { fprintf(stderr,"Plaintext length set failed\n"); ERR_print_errors_fp(stderr); test1_exit(12); } if (an && !EVP_EncryptUpdate(&ctx,NULL,&outl,aad,an)) { fprintf(stderr,"AAD set failed\n"); ERR_print_errors_fp(stderr); test1_exit(13); } } else if(!EVP_DecryptInit_ex(&ctx,c,NULL,key,iv)) { fprintf(stderr,"DecryptInit failed\n"); ERR_print_errors_fp(stderr); test1_exit(11); } EVP_CIPHER_CTX_set_padding(&ctx,0); if(!EVP_DecryptUpdate(&ctx,out,&outl,ciphertext,cn)) { fprintf(stderr,"Decrypt failed\n"); ERR_print_errors_fp(stderr); test1_exit(6); } if(mode != EVP_CIPH_CCM_MODE && !EVP_DecryptFinal_ex(&ctx,out+outl,&outl2)) { fprintf(stderr,"DecryptFinal failed\n"); ERR_print_errors_fp(stderr); test1_exit(7); } if(outl+outl2 != pn) { fprintf(stderr,"Plaintext length mismatch got %d expected %d\n", outl+outl2,pn); test1_exit(8); } if(memcmp(out,plaintext,pn)) { fprintf(stderr,"Plaintext mismatch\n"); hexdump(stderr,"Got",out,pn); hexdump(stderr,"Expected",plaintext,pn); test1_exit(9); } } EVP_CIPHER_CTX_cleanup(&ctx); printf("\n"); }