TNB Library
TnbStringCipher.h
[詳解]
1#pragma once
13#include "TnbStr.h"
14#include "TnbException.h"
15
16
17
18//TNB Library
19namespace TNB
20{
21
22
23
37{
38public:
39
46 void SetKey(const CAscii& ascKey)
47 {
48 m_ascKey = ascKey;
49 }
50
57 CAscii Encode(LPCSTR lpsz) const
58 {
59 return m_Shift(lpsz, true);
60 }
61
68 CAscii Decode(LPCSTR lpsz) const
69 {
70 return m_Shift(lpsz, false);
71 }
72
73private:
84 static int ms_RangeShift(int c, int iShift, int iMin, int iMax)
85 {
86 ASSERTLIB(iMin < iMax);
87 if ( c < iMin || c > iMax )
88 {
89 return -1;
90 }
91 int iRange = iMax - iMin;
92 if ( iShift >= 0 )
93 {
94 iShift %= iRange;
95 }
96 else
97 {
98 iShift = -((-iShift) % iRange);
99 }
100 //
101 int iCode = (c - iMin) + iShift;
102 while ( iCode < 0x0000 )
103 {
104 iCode += iRange;
105 }
106 while ( iCode >= iRange )
107 {
108 iCode -= iRange;
109 }
110 ASSERTLIB( (iCode + iMin) >= iMin && (iCode + iMin) < iMax );
111 return iCode + iMin;
112 }
113
122 static BYTE ms_ShiftChar(BYTE c, int iShift)
123 {
124 int r = ms_RangeShift(c, iShift, 0x20, 0x80);
125 if ( r < 0 ) { r = ms_RangeShift(c, iShift, 0x81, 0x9F); }
126 if ( r < 0 ) { r = ms_RangeShift(c, iShift, 0xA0, 0xDF); }
127 if ( r < 0 ) { r = ms_RangeShift(c, iShift, 0xE0, 0xFB); }
128 return ( r < 0 ) ? c : static_cast<BYTE>(r);
129 }
130
138 CAscii m_Shift(LPCSTR lpsz, bool boIsEnc) const
139 {
140 if ( m_ascKey.IsEmpty() )
141 {
142 ASSERT0(false, "CCipherData", "暗号、復号キーが指定されていません。");
143 throw CEmptyException();
144 }
145 const BYTE* B = reinterpret_cast<const BYTE*>(LPCSTR(m_ascKey));
146 size_t iKeySize = m_ascKey.GetLength();
147 CAscii str;
148 size_t iLen = STRLIB::GetLen(lpsz);
149 if ( iLen > 0 )
150 {
151 char* P = str.GetBuffer(iLen);
152 if ( boIsEnc )
153 {
154 loop ( i, iLen )
155 {
156 P[i] = ms_ShiftChar(lpsz[i], B[i % iKeySize]);
157 }
158 }
159 else
160 {
161 loop ( i, iLen )
162 {
163 P[i] = ms_ShiftChar(lpsz[i], -B[i % iKeySize]);
164 }
165 }
166 P[iLen] = 0;
167 str.ReleaseBuffer();
168 }
169 return str;
170 }
171
172 CAscii m_ascKey;
173};
174
175
176
177};//TNB
#define loop(VAR, CNT)
loop構文.
Definition: TnbDef.h:343
例外状態管理関係のヘッダ
文字列管理関係のヘッダ
取得要素(空き)無し例外
Definition: TnbException.h:107
bool IsEmpty(void) const
[確認] 空チェック
Definition: TnbStr.h:528
void ReleaseBuffer(void)
[操作] 割り当てたバッファを開放.
Definition: TnbStr.h:954
size_t GetLength(void) const
[取得] 文字列長
Definition: TnbStr.h:518
TYP * GetBuffer(size_t iLength=0)
[操作] 書き込みバッファ要求.
Definition: TnbStr.h:914
文字列暗号復号クラス
CAscii Encode(LPCSTR lpsz) const
[設定] 暗号化
void SetKey(const CAscii &ascKey)
[設定] キー設定.
CAscii Decode(LPCSTR lpsz) const
[設定] 復号化
size_t GetLen(LPCSTR lpsz)
[計算] 文字列長計算(ASCII/SJIS用)
Definition: TnbStrLib.h:44
TNB Library
Definition: TnbDoxyTitle.txt:2