openssl-enc.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. /* LibTomCrypt, modular cryptographic library -- Tom St Denis */
  2. /* SPDX-License-Identifier: Unlicense */
  3. /*
  4. * Demo to do the rough equivalent of:
  5. *
  6. * openssl enc -aes-256-cbc -pass pass:foobar -in infile -out outfile -p
  7. *
  8. * Compilation:
  9. *
  10. * $(CC) -I /path/to/headers -L .../libs \
  11. * -o openssl-enc \
  12. * openssl-enc.c -ltomcrypt
  13. *
  14. * Usage:
  15. *
  16. * ./openssl-enc <enc|dec> infile outfile "passphrase" [salt]
  17. *
  18. * If provided, the salt must be EXACTLY a 16-char hex string.
  19. *
  20. * Demo is an example of:
  21. *
  22. * - (When decrypting) yanking salt out of the OpenSSL "Salted__..." header
  23. * - OpenSSL-compatible key derivation (in OpenSSL's modified PKCS#5v1 approach)
  24. * - Grabbing an Initialization Vector from the key generator
  25. * - Performing simple block encryption using AES
  26. * - PKCS#7-type padding (which hopefully can get ripped out of this demo and
  27. * made a libtomcrypt thing someday).
  28. *
  29. * This program is free for all purposes without any express guarantee it
  30. * works. If you really want to see a license here, assume the WTFPL :-)
  31. *
  32. * BJ Black, [email protected], https://wjblack.com
  33. *
  34. * BUGS:
  35. * Passing a password on a command line is a HORRIBLE idea. Don't use
  36. * this program for serious work!
  37. */
  38. #include <tomcrypt.h>
  39. #ifndef LTC_RIJNDAEL
  40. #error Cannot compile this demo; Rijndael (AES) required
  41. #endif
  42. #ifndef LTC_CBC_MODE
  43. #error Cannot compile this demo; CBC mode required
  44. #endif
  45. #ifndef LTC_PKCS_5
  46. #error Cannot compile this demo; PKCS5 required
  47. #endif
  48. #ifndef LTC_RNG_GET_BYTES
  49. #error Cannot compile this demo; random generator required
  50. #endif
  51. #ifndef LTC_MD5
  52. #error Cannot compile this demo; MD5 required
  53. #endif
  54. /* OpenSSL by default only runs one hash round */
  55. #define OPENSSL_ITERATIONS 1
  56. /* Use aes-256-cbc, so 256 bits of key, 128 of IV */
  57. #define KEY_LENGTH (256>>3)
  58. #define IV_LENGTH (128>>3)
  59. /* PKCS#5v1 requires exactly an 8-byte salt */
  60. #define SALT_LENGTH 8
  61. /* The header OpenSSL puts on an encrypted file */
  62. static char salt_header[] = { 'S', 'a', 'l', 't', 'e', 'd', '_', '_' };
  63. #include <errno.h>
  64. #include <stdio.h>
  65. #include <string.h>
  66. /* A simple way to handle the possibility that a block may increase in size
  67. after padding. */
  68. union paddable {
  69. unsigned char unpad[1024];
  70. unsigned char pad[1024+MAXBLOCKSIZE];
  71. };
  72. /*
  73. * Print usage and exit with a bad status (and perror() if any errno).
  74. *
  75. * Input: argv[0] and the error string
  76. * Output: <no return>
  77. * Side Effects: print messages and barf (does exit(3))
  78. */
  79. void barf(const char *pname, const char *err)
  80. {
  81. printf("Usage: %s <enc|dec> infile outfile passphrase [salt]\n", pname);
  82. printf("\n");
  83. printf(" # encrypts infile->outfile, random salt\n");
  84. printf(" %s enc infile outfile \"passphrase\"\n", pname);
  85. printf("\n");
  86. printf(" # encrypts infile->outfile, salt from cmdline\n");
  87. printf(" %s enc infile outfile pass 0123456789abcdef\n", pname);
  88. printf("\n");
  89. printf(" # decrypts infile->outfile, pulls salt from infile\n");
  90. printf(" %s dec infile outfile pass\n", pname);
  91. printf("\n");
  92. printf(" # decrypts infile->outfile, salt specified\n");
  93. printf(" # (don't try to read the salt from infile)\n");
  94. printf(" %s dec infile outfile pass 0123456789abcdef"
  95. "\n", pname);
  96. printf("\n");
  97. printf("Application Error: %s\n", err);
  98. if(errno)
  99. perror(" System Error");
  100. exit(-1);
  101. }
  102. /*
  103. * Parse a salt value passed in on the cmdline.
  104. *
  105. * Input: string passed in and a buf to put it in (exactly 8 bytes!)
  106. * Output: CRYPT_OK if parsed OK, CRYPT_ERROR if not
  107. * Side Effects: none
  108. */
  109. int parse_hex_salt(unsigned char *in, unsigned char *out)
  110. {
  111. int idx;
  112. for(idx=0; idx<SALT_LENGTH; idx++)
  113. if(sscanf((char*)in+idx*2, "%02hhx", out+idx) != 1)
  114. return CRYPT_ERROR;
  115. return CRYPT_OK;
  116. }
  117. /*
  118. * Parse the Salted__[+8 bytes] from an OpenSSL-compatible file header.
  119. *
  120. * Input: file to read from and a to put the salt in (exactly 8 bytes!)
  121. * Output: CRYPT_OK if parsed OK, CRYPT_ERROR if not
  122. * Side Effects: infile's read pointer += 16
  123. */
  124. int parse_openssl_header(FILE *in, unsigned char *out)
  125. {
  126. unsigned char tmp[SALT_LENGTH];
  127. if(fread(tmp, 1, sizeof(tmp), in) != sizeof(tmp))
  128. return CRYPT_ERROR;
  129. if(memcmp(tmp, salt_header, sizeof(tmp)))
  130. return CRYPT_ERROR;
  131. if(fread(tmp, 1, sizeof(tmp), in) != sizeof(tmp))
  132. return CRYPT_ERROR;
  133. memcpy(out, tmp, sizeof(tmp));
  134. return CRYPT_OK;
  135. }
  136. /*
  137. * Dump a hexed stream of bytes (convenience func).
  138. *
  139. * Input: buf to read from, length
  140. * Output: none
  141. * Side Effects: bytes printed as a hex blob, no lf at the end
  142. */
  143. void dump_bytes(unsigned char *in, unsigned long len)
  144. {
  145. unsigned long idx;
  146. for(idx=0; idx<len; idx++)
  147. printf("%02hhX", *(in+idx));
  148. }
  149. /*
  150. * Pad or unpad a message using PKCS#7 padding.
  151. * Padding will add 1-(blocksize) bytes and unpadding will remove that amount.
  152. * Set is_padding to 1 to pad, 0 to unpad.
  153. *
  154. * Input: paddable buffer, size read, block length of cipher, mode
  155. * Output: number of bytes after padding resp. after unpadding
  156. * Side Effects: none
  157. */
  158. static size_t s_pkcs7_pad(union paddable *buf, size_t nb, int block_length,
  159. int is_padding)
  160. {
  161. unsigned long length;
  162. if(is_padding) {
  163. length = sizeof(buf->pad);
  164. if (padding_pad(buf->pad, nb, &length, block_length) != CRYPT_OK)
  165. return 0;
  166. return length;
  167. } else {
  168. length = nb;
  169. if (padding_depad(buf->pad, &length, 0) != CRYPT_OK)
  170. return 0;
  171. return length;
  172. }
  173. }
  174. /*
  175. * Perform an encrypt/decrypt operation to/from files using AES+CBC+PKCS7 pad.
  176. * Set encrypt to 1 to encrypt, 0 to decrypt.
  177. *
  178. * Input: in/out files, key, iv, and mode
  179. * Output: CRYPT_OK if no error
  180. * Side Effects: bytes slurped from infile, pushed to outfile, fds updated.
  181. */
  182. int do_crypt(FILE *infd, FILE *outfd, unsigned char *key, unsigned char *iv,
  183. int encrypt)
  184. {
  185. union paddable inbuf, outbuf;
  186. int cipher, ret;
  187. symmetric_CBC cbc;
  188. size_t nb;
  189. /* Register your cipher! */
  190. cipher = register_cipher(&aes_desc);
  191. if(cipher == -1)
  192. return CRYPT_INVALID_CIPHER;
  193. /* Start a CBC session with cipher/key/val params */
  194. ret = cbc_start(cipher, iv, key, KEY_LENGTH, 0, &cbc);
  195. if( ret != CRYPT_OK )
  196. return -1;
  197. do {
  198. /* Get bytes from the source */
  199. nb = fread(inbuf.unpad, 1, sizeof(inbuf.unpad), infd);
  200. if(!nb)
  201. return encrypt ? CRYPT_OK : CRYPT_ERROR;
  202. /* Barf if we got a read error */
  203. if(ferror(infd))
  204. return CRYPT_ERROR;
  205. if(encrypt) {
  206. /* We're encrypting, so pad first (if at EOF) and then
  207. crypt */
  208. if(feof(infd))
  209. nb = s_pkcs7_pad(&inbuf, nb,
  210. aes_desc.block_length, 1);
  211. ret = cbc_encrypt(inbuf.pad, outbuf.pad, nb, &cbc);
  212. if(ret != CRYPT_OK)
  213. return ret;
  214. } else {
  215. /* We're decrypting, so decrypt and then unpad if at
  216. EOF */
  217. ret = cbc_decrypt(inbuf.unpad, outbuf.unpad, nb, &cbc);
  218. if( ret != CRYPT_OK )
  219. return ret;
  220. if(feof(infd))
  221. nb = s_pkcs7_pad(&outbuf, nb,
  222. aes_desc.block_length, 0);
  223. if(nb == 0)
  224. /* The file didn't decrypt correctly */
  225. return CRYPT_ERROR;
  226. }
  227. /* Push bytes to outfile */
  228. if(fwrite(outbuf.unpad, 1, nb, outfd) != nb)
  229. return CRYPT_ERROR;
  230. } while(!feof(infd));
  231. /* Close up */
  232. cbc_done(&cbc);
  233. return CRYPT_OK;
  234. }
  235. /* Convenience macro for the various barfable places below */
  236. #define BARF(a) { \
  237. if(infd) fclose(infd); \
  238. if(outfd) { fclose(outfd); remove(argv[3]); } \
  239. barf(argv[0], a); \
  240. }
  241. /*
  242. * The main routine. Mostly validate cmdline params, open files, run the KDF,
  243. * and do the crypt.
  244. */
  245. int main(int argc, char *argv[]) {
  246. unsigned char salt[SALT_LENGTH];
  247. FILE *infd = NULL, *outfd = NULL;
  248. int encrypt = -1;
  249. int hash = -1;
  250. int ret;
  251. unsigned char keyiv[KEY_LENGTH + IV_LENGTH];
  252. unsigned long keyivlen = (KEY_LENGTH + IV_LENGTH);
  253. unsigned char *key, *iv;
  254. /* Check proper number of cmdline args */
  255. if(argc < 5 || argc > 6)
  256. BARF("Invalid number of arguments");
  257. /* Check proper mode of operation */
  258. if (!strncmp(argv[1], "enc", 3))
  259. encrypt = 1;
  260. else if(!strncmp(argv[1], "dec", 3))
  261. encrypt = 0;
  262. else
  263. BARF("Bad command name");
  264. /* Check we can open infile/outfile */
  265. infd = fopen(argv[2], "rb");
  266. if(infd == NULL)
  267. BARF("Could not open infile");
  268. outfd = fopen(argv[3], "wb");
  269. if(outfd == NULL)
  270. BARF("Could not open outfile");
  271. /* Get the salt from wherever */
  272. if(argc == 6) {
  273. /* User-provided */
  274. if(parse_hex_salt((unsigned char*) argv[5], salt) != CRYPT_OK)
  275. BARF("Bad user-specified salt");
  276. } else if(!strncmp(argv[1], "enc", 3)) {
  277. /* Encrypting; get from RNG */
  278. if(rng_get_bytes(salt, sizeof(salt), NULL) != sizeof(salt))
  279. BARF("Not enough random data");
  280. } else {
  281. /* Parse from infile (decrypt only) */
  282. if(parse_openssl_header(infd, salt) != CRYPT_OK)
  283. BARF("Invalid OpenSSL header in infile");
  284. }
  285. /* Fetch the MD5 hasher for PKCS#5 */
  286. hash = register_hash(&md5_desc);
  287. if(hash == -1)
  288. BARF("Could not register MD5 hash");
  289. /* Set things to a sane initial state */
  290. zeromem(keyiv, sizeof(keyiv));
  291. key = keyiv + 0; /* key comes first */
  292. iv = keyiv + KEY_LENGTH; /* iv comes next */
  293. /* Run the key derivation from the provided passphrase. This gets us
  294. the key and iv. */
  295. ret = pkcs_5_alg1_openssl((unsigned char*)argv[4], XSTRLEN(argv[4]), salt,
  296. OPENSSL_ITERATIONS, hash, keyiv, &keyivlen );
  297. if(ret != CRYPT_OK)
  298. BARF("Could not derive key/iv from passphrase");
  299. /* Display the salt/key/iv like OpenSSL cmdline does when -p */
  300. printf("salt="); dump_bytes(salt, sizeof(salt)); printf("\n");
  301. printf("key="); dump_bytes(key, KEY_LENGTH); printf("\n");
  302. printf("iv ="); dump_bytes(iv, IV_LENGTH ); printf("\n");
  303. /* If we're encrypting, write the salt header as OpenSSL does */
  304. if(!strncmp(argv[1], "enc", 3)) {
  305. if(fwrite(salt_header, 1, sizeof(salt_header), outfd) !=
  306. sizeof(salt_header) )
  307. BARF("Error writing salt header to outfile");
  308. if(fwrite(salt, 1, sizeof(salt), outfd) != sizeof(salt))
  309. BARF("Error writing salt to outfile");
  310. }
  311. /* At this point, the files are open, the salt has been figured out,
  312. and we're ready to pump data through crypt. */
  313. /* Do the crypt operation */
  314. if(do_crypt(infd, outfd, key, iv, encrypt) != CRYPT_OK)
  315. BARF("Error during crypt operation");
  316. /* Clean up */
  317. fclose(infd); fclose(outfd);
  318. return 0;
  319. }