问题
my plaintext is first converted to binary text, then it should be divided into 64 bit blocks and the key has to encrypted tese blocks separately. for example, if my text has 90 bits it should be supplemented with zeros so that it has 128 bits. I do not know how to do this. here is my code:
string ifile = "filetxt.txt";
string ofile = "file2.txt";
string key = "keywordd";
vector<int> k;
vector<int> txt;
char text;
vector<int> o;
int i;
int c = 0;
int d = 1;
void f() {
ifstream ist ("filetxt.txt");
ofstream ost ("file2.txt");
int a[64], i;
while (ist >> text) {
for(char& text : key) {
for(i=0; i < 8; i++){
a[i] = text%2;
text = text/2;
}
for(i=i-1; i >= 0 ;i--){
k.push_back(a[i]);
}
}
if (ist) {
for(i=0; i < 8; i++){
a[i] = text%2;
text = text/2;
}
for(i=i-1 ;i >= 0 ;i--){
txt.push_back(a[i]);
}
for(int j = 0; j < 8; j++) {
if(k[j] == txt[j]) {
o.push_back(c);
} else if (k[j] != txt[j]) {
o.push_back(d);
}
}
for(i=0; i<8; i++) {
ost << o[i];
}
for(i=0; i<8; i++) {
cout << o[i];
}
}
}
cout << endl;
for(i=0; i<64; i++) {
cout << k[i];
}
cout << endl;
for(i=0; i<64; i++) {
cout << txt[i];
}
}
int main()
{
f();
return 0;
}
i was to do something like this:
if (txt.size()< 64){
for(i= 0; i< 64- txt.size();i++){
txt.push_back(c);
}
}
i think that the problem is in the txt vector because if i want to print it i
回答1:
It's very easy:
if (txt.size()< 64)
txt.resize(64);
This will simply pad out the vector with the default value for int
, which is 0.
If you want a value other than 0 (c
as your code suggests) then it's:
if (txt.size()< 64)
txt.resize(64, c);
回答2:
What you want is std::vector::resize. By default it will increase the size of the vector to the size requested (if the vector is less then said size), and any elements added will be value initialized, which for an int
means zero initialized. That gives you
if (txt.size() % 64 != 0)
txt.resize(txt.size() + (64 - (txt.size() % 64)));
Also note that 64 int
's is not 64 bits. An int
has to have at least a size of 16 bits meaning 64 of them will be at least 512 bits. If you actually need to have 64 bit chunks, you should be using a std::uint64_t for the bit chunks (or something like it)
回答3:
Do something like the following as last step:
if ((txt.size() % 64) != 0){
for(i= 0; i< 64-((txt.size() % 64)); i++){
txt.push_back(c);
}
}
This way, no matter which length your plaintext is, your txt
vector will always end with a multiple of 64 length padded with zeros (c
) if necessary.
来源:https://stackoverflow.com/questions/60867330/padding-in-vector-with-zeros