9#include "kwalletbackend_debug.h"
12CipherBlockChain::CipherBlockChain(BlockCipher *cipher,
bool useECBforReading) :
14 , _useECBforReading(useECBforReading)
19 _reader = _writer = 0L;
21 _blksz = cipher->blockSize();
25CipherBlockChain::~CipherBlockChain()
27 delete[](
char *)_register;
29 delete[](
char *)_next;
33bool CipherBlockChain::setKey(
void *key,
int bitlength)
36 return _cipher->setKey(key, bitlength);
41int CipherBlockChain::keyLen()
const
44 return _cipher->keyLen();
49bool CipherBlockChain::variableKeyLen()
const
52 return _cipher->variableKeyLen();
57bool CipherBlockChain::readyToGo()
const
60 return _cipher->readyToGo();
65void CipherBlockChain::initRegister() {
66 if (_register ==
nullptr) {
67 size_t registerLen = _cipher->blockSize();
68 _register =
new unsigned char[registerLen];
71 memset(_register, 0, _len);
74int CipherBlockChain::encrypt(
void *block,
int len)
76 if (_cipher && !_reader) {
83 if ((len % _len) >0) {
84 qCDebug(KWALLETBACKEND_LOG) <<
"Block length given encrypt (" << len <<
") is not a multiple of " << _len;
88 char *elemBlock =
static_cast<char*
>(block);
89 for (
int b = 0; b < len/_len; b++) {
92 char *tb =
static_cast<char*
>(elemBlock);
93 for (
int i = 0; i < _len; i++) {
94 *tb++ ^= ((
char *)_register)[i];
97 rc = _cipher->encrypt(elemBlock, _len);
100 memcpy(_register, elemBlock, _len);
112int CipherBlockChain::decryptECB(
void *block,
int len) {
113 if (_cipher && !_writer) {
119 _register =
new unsigned char[len];
121 memset(_register, 0, len);
122 }
else if (len > _len) {
127 _next =
new unsigned char[_len];
129 memcpy(_next, block, _len);
131 rc = _cipher->decrypt(block, len);
135 char *tb = (
char *)block;
136 for (
int i = 0; i < len; i++) {
137 tb[i] ^= ((
char *)_register)[i];
151int CipherBlockChain::decrypt(
void *block,
int len)
153 if (_useECBforReading) {
154 qCDebug(KWALLETBACKEND_LOG) <<
"decrypting using ECB!";
155 return decryptECB(block, len);
158 if (_cipher && !_writer) {
165 if ((len % _len) >0) {
166 qCDebug(KWALLETBACKEND_LOG) <<
"Block length given for decrypt (" << len <<
") is not a multiple of " << _len;
170 char *elemBlock =
static_cast<char*
>(block);
171 for (
int b = 0; b < len/_len; b++) {
172 if (_next ==
nullptr) {
173 _next =
new unsigned char[_len];
175 memcpy(_next, elemBlock, _len);
177 int bytesDecrypted = _cipher->decrypt(elemBlock, _len);
179 if (bytesDecrypted != -1) {
180 rc += bytesDecrypted;
182 char *tb = (
char *)elemBlock;
183 for (
int i = 0; i < _len; i++) {
184 *tb++ ^= ((
char *)_register)[i];