暗号化コード
ゲームで使われる独自スクリプトやテキスト型データはよくfgets()で一行ずつ読み込んでなんたらやるように書かれます。
そのfgets()の書き方を流用できる暗号版MyFGetS()を作りました。
最終コカラゲ暗号システムとはまた別です。
すきにつかってね!!
//KAngo.h #ifndef __KANGO_H_INCLUDED__ #define __KANGO_H_INCLUDED__ #include <stdio.h> #include <stdlib.h> class CKAngo { private: int N_TESTS; char ttable[27]; int counter; char CKAngo::Char2Char_Enc(char ch); char CKAngo::Char2Char_Dec(char ch); int CKAngo::MyFGetCh(char *buf, FILE *f); public: CKAngo() { N_TESTS = 27; counter = 0; const char ttable_b[27] = { 91, 87, 49, 23, 74, 77, 41, 33, 66, 61, 97, 10, 9, 24, 91, 53, 87, 62, 93, 63, 49, 14, 28, 10, 78, 69, 62, }; for(int i=0;i<N_TESTS;i++) { ttable[i] = ttable_b[i]; } } void ResetCounter(); int MyFGetStr(char *buf, FILE *f); void FileToGetAngo(char *filename); void FileToPutAngo(char *filename, char *outfilename); }; #endif //__KANGO_H_INCLUDED__
KAngo.cpp
#include "KAngo.h" char CKAngo::Char2Char_Enc(char ch) { char rval; rval = ch ^ ttable[counter]; counter++; if (counter >= N_TESTS) counter = 0; return rval; } char CKAngo::Char2Char_Dec(char ch) { char rval; rval = ch ^ ttable[counter]; counter++; if (counter >= N_TESTS) counter = 0; return rval; } int CKAngo::MyFGetCh(char *buf, FILE *f) { int nreaded; char ch, dch; nreaded = fread(&ch, sizeof(char), 1, f); if (nreaded < 1) { return 0; } dch = Char2Char_Dec(ch); if (dch == '\n' || dch == '\r') { return -1; } *buf = dch; return 1; } int CKAngo::MyFGetStr(char *buf, FILE *f) { int readed = 0; // ok the word must be "read", I know; while(1) { int v; char ch; v = MyFGetCh(&ch, f); if (v == -1)//Return { *buf = 0; break; } if (v == 0)//EOF { *buf = 0; if (!readed) { return 0; } else { break; } } *buf = ch; readed++; buf++; } return 1; } void CKAngo::ResetCounter() { counter = 0; } void CKAngo::FileToGetAngo(char *filename) { char buf[4096]; FILE *f; counter = 0; f = fopen(filename, "rb"); if (!f) return; while(MyFGetStr(buf, f)) { puts(buf); } fclose(f); } void CKAngo::FileToPutAngo(char *filename, char *outfilename) { FILE *f; FILE *fdest; char buf[1024]; counter = 0; f = fopen(filename, "rt"); if (f == 0) return; fdest = fopen(outfilename, "wb"); if (fdest == 0) return; while(fgets(buf, 1024, f)) { if (!buf[0]) continue; char *str = buf; while(*str) { char ch = Char2Char_Enc(*str); fwrite(&ch, sizeof(char), 1, fdest); str++; } } fclose(f); fclose(fdest); return; }
使い方の例。
テキストファイルzzz.txtを暗号化してzzza.txtに書き込み、
そのあとzzza.txtを読み込んで表示します。
//Test.cpp #include "KAngo.h" void main() { CKAngo angob; angob.FileToPutAngo("zzz.txt", "zzza.txt"); angob.ResetCounter(); angob.FileToGetAngo("zzza.txt"); }