mycipher_fp.c

最終更新:2009/10/10

mycipher_fp.c

001: /* mycipher_fp.c
002:  * EVP 関数による暗号化・復号のサンプル(FILE*版)
003:  */
004: 
005: #include <openssl/evp.h>
006: 
007: #include "mycipher_fp.h"
008: 
009: /*
010:  * ファイルを暗号化・復号する関数(FILE*版)
011:  * 返り値:
012:  * 0 失敗
013:  * 1 成功
014:  */
015: 
016: int kencdec_from_FP_to_FP(
017:   char *cipher_alg         /* IN:暗号アルゴリズム。OpenSSL の指定に基づく。暗号名+"-"+鍵長+"-"+暗号モード */
018:   , unsigned char *keyData /* IN:暗号鍵のオクテット列 */
019:   , int keyLen             /* IN:暗号鍵の長さ(オクテット長) */
020:   , unsigned char *ivData  /* IN:初期化ベクトルのオクテット列 */
021:   , int ivLen              /* IN:初期化ベクトルの長さ(オクテット長) */
022:   , FILE *fpIn             /* IN:入力ファイルポインタ */
023:   , FILE *fpOut            /* OUT:出力ファイルポインタ */
024:   , int type               /* IN:処理タイプ。1:暗号化、0:復号 */
025: ) {
026:   int result = 1;
027: 
028:   const EVP_CIPHER *evp_cipher = NULL;
029:   EVP_CIPHER_CTX ctx;
030: 
031:   unsigned char inBuf[ENCDEC_BUFF_SIZE];
032:   unsigned char outBuf[ENCDEC_BUFF_SIZE];
033: 
034:   int inLen = 0;
035:   int outLen=0;
036: 
037:   if (NULL == cipher_alg || NULL == fpIn || NULL == fpOut) {
038: if(1)fprintf (stderr, "ERROR: kencdec_from_FP_to_FP: argument null.\n");
039:     return 0;
040:   }
041: 
042:   OpenSSL_add_all_ciphers();
043:   
044:   if (NULL == (evp_cipher = EVP_get_cipherbyname(cipher_alg))) {
045: if(1)fprintf(stderr, "ERROR: kencdec_from_FP_to_FP: EVP_get_cipherbyname\n");
046:     return 0;
047:   }
048:   EVP_CIPHER_CTX_init(&ctx);
049:   
050:   if (!EVP_CipherInit(&ctx, evp_cipher, keyData, ivData, type/*ENCRYPT:1,DECRYPT:0*/)) {
051: if(1)fprintf(stderr, "ERROR: kencdec_from_FP_to_FP: EVP_CipherInit\n");
052:     result = 0;
053:     goto _FINALLY_;
054:   }
055:   
056:   EVP_CIPHER_CTX_set_padding(&ctx, 1);
057: 
058:   while ((inLen = fread(inBuf, sizeof(unsigned char), ENCDEC_BUFF_SIZE, fpIn)) > 0) {
059:     outLen = 0;
060:     if (EVP_CipherUpdate(&ctx, outBuf, &outLen, inBuf, inLen)) {
061:       fwrite(outBuf, sizeof(unsigned char), outLen, fpOut);
062:     } else {
063: if(1)fprintf(stderr, "ERROR: kencdec_from_FP_to_FP: EVP_CipherUpdate\n");
064:       result = 0;
065:       goto _FINALLY_;
066:     }
067:   }
068: 
069:   outLen = 0;
070:   if (EVP_CipherFinal(&ctx, outBuf, &outLen)) {
071:     fwrite(outBuf, sizeof(unsigned char), outLen, fpOut);
072:   } else {
073: if(1)fprintf(stderr, "ERROR: kencdec_from_FP_to_FP: EVP_CipherFinal\n");
074:     result = 0;
075:   }
076: 
077:   _FINALLY_:
078: 
079:   EVP_CIPHER_CTX_cleanup(&ctx);
080: 
081:   return result;
082: 
083: }
Copyright (C) KAKU PROJECT (2009)KAKU PROJECT (2009)