This problem bothered me for an hour when I was programming, but I still didn't know the error of the original method after solving it.
void generate_r_vector(char (*r_vector)[17],char *random_r) {
BIGNUM* vector[127];
char r_v[128][17];
char flag[17];
memset(flag, 0, sizeof(flag));
int bits = 128;
int top = 0;
int bottom = 0;
for (int i = 0; i < 127; i++) {
vector[i] = BN_new();
BN_rand(vector[i], bits, top, bottom);
memset(r_v[i], 0, sizeof(r_v[i]));
BN_bn2bin(vector[i], r_v[i]);
}
memset(r_v[127], 0, sizeof(r_v[127]));
for (int i = 0; i < 127; i++) {
for (int j = 0; j < 16; j++) {
flag[j] = flag[j] ^ r_v[i][j];
}
}
for (int i = 0; i < 16; i++) {
r_v[127][i] = flag[i] ^ random_r[i];
}
for (int i = 0; i < 128; i++) {
memcpy(r_vector[i], r_v[i], 17);
}
}
Using memcpy to copy these arrays, when XOR in the main function, you can get the original string random_r.
But using the strcpy function to copy these arrays in the main function XOR, can not get the original random_r.
What I learned about OpenSSL:here, a 128 bit large number is converted into binary, and then every 4 bits are converted into a decimal, which is stored in the char array.
Memcpy copies by byte, while strcpy can only copy strings.
I can't understand why the XOR results of the two copy methods are different when they are both stored in char arrays.
My English level is not good, I hope you programmers can understand my expression. I sincerely hope you can answer my question. thank you
=======================2021/2/21 updata=====================================
I provide a program that can run directly, hoping to alleviate the problems caused by my unclear expression.
int main() {
char* random_r="1234567891234567";//长度16 算上'\0'17
char r_vector[128][17];
BIGNUM* vector[127];
char r_v[128][17];
char flag[17];//判断是否一致
memset(flag, 0, sizeof(flag));
int bits = 128;
int top = 0;
int bottom = 0;
for (int i = 0; i < 127; i++) {
vector[i] = BN_new();
BN_rand(vector[i], bits, top, bottom);
memset(r_v[i], 0, sizeof(r_v[i]));
BN_bn2bin(vector[i], r_v[i]);
}
memset(r_v[127], 0, sizeof(r_v[127]));
for (int i = 0; i < 127; i++) {
for (int j = 0; j < 16; j++) {
flag[j] = flag[j] ^ r_v[i][j];
}
}
for (int i = 0; i < 16; i++) {
r_v[127][i] = flag[i] ^ random_r[i];
}
//至此生成了128个向量,这些向量的异或之和正好是random_r的值,ans可以验证这个结论
char ans[17];
memset(ans, 0, sizeof(ans));
for (int i = 0; i < 128; i++) {
for (int j = 0; j < 16; j++) {
ans[j] = ans[j] ^ r_v[i][j];
}
}
printf("the target XOR result is:%s\n", ans);//
//下面使用memcpy的形式拷贝并求异或值
for (int i = 0; i < 128; i++) {
memcpy(r_vector[i], r_v[i], 17);//逐字节拷贝解决问题strcpy会出现问题,原因未知
}
memset(ans, 0, sizeof(ans));
for (int i = 0; i < 128; i++) {
for (int j = 0; j < 16; j++) {
ans[j] = ans[j] ^ r_vector[i][j];
}
}
printf("using memcpy copying and the result is:%s\n", ans);//这是正确的结果
memset(r_vector, 0, sizeof(r_vector));
for (int i = 0; i < 128; i++) {
strcpy(r_vector[i], r_v[i]);//strcpy会出现问题,原因未知
}
memset(ans, 0, sizeof(ans));
for (int i = 0; i < 128; i++) {
for (int j = 0; j < 16; j++) {
ans[j] = ans[j] ^ r_vector[i][j];
}
}
printf("using strcpy copying and the result is:%s\n", ans);
int err_count = 0;
for (int i = 0; i < 128; i++) {
if (strcmp(r_vector[i], r_v[i]) != 0) err_count++;
}
printf("after using strcpy() each vector using strcmp() with orignal r_v,the different vector nums:%d\n", err_count);
system("pause");
return 0;
}
Running results in vs2019
the target XOR result is:1234567891234567
using memcpy copying and the result is:1234567891234567
using strcpy copying and the result is:12eH⊙碡?H-c纫
after using strcpy() each vector using strcmp() with orignal r_v,the different vector nums:0
What causes the difference between memcpy and strcpy in copying openssl BIGNUM
The comment "BIGNUM values are not C strings, so strcpy() won't work." may be not enough to enlighten you.
BIGNUM values can contain a byte with all bits set to 0, called the null character, and since that is used to terminate a character string, strcpy() stops there and doesn't copy the rest of the BIGNUM value.
Even when strcpy and memcpy are both used for char arrays, they don't do exactly the same thing. memcpy copies a fixed number of bytes, which you give as the third argument. strcpy doesn't just copy from one char array or pointer to another, it figures out how much to copy in a completely different way, namely by checking for a 0 value in the chars to copy.
Even though r_vector points to char arrays, they don't have to be strings: If they are not 0-terminated or have 0 values at other positions things will behave differently than for a string.
Related
I'm trying to make a code which converts some decimal numbers to bits.
There are more simple ways to reach this result but I'm poking around and joking with memory in C.
int ** decimalToBits(int *number,int size){
int **bits = (int **)malloc(sizeof(*bits)*size), i = 0;
for (int j = 0; j < size; j++) {
int * temp = (int *)malloc(sizeof(int));
while (number[j] >= 1) {
temp[i++] = number[j] % 2;
number[j] /= 2;
realloc(temp, sizeof(int));
}
printf("\n");
bits[j] = (int *) malloc(sizeof(int)*i);
for (int k = i-1; k >= 0; k--){
bits[j][k] = temp[k];
printf("%d" ,bits[j][k]);
}
i = 0;
}
return bits;
}
I'm having some allocation problems, first of all I'm going to explain the idea:
I pass to the function multiple numbers, so for example:
int numbers[2] = {23,73};
decimalToBits(numbers,2);
Each converted number will be stored in **bits double pointer, so bits[0] will contain the number 23 converted, and bits[1] will contain 73 converted as well.
The problem shows up when I do bits[j] = (int *) malloc(sizeof(int)*i); call,
because this seems to let the temp pointer to be overwritten with some random numbers. In fact if I remove the bits[j] = (int *) malloc(sizeof(int)*i); and bits[j][k] = temp[k]; lines and I replace printf("%d" ,bits[j][k]); with printf("%d" ,temp[k]);
the code seems to have a good behavior, and it gives me the correct output:
10111
1001001
I also noticed that allocating the bits[j] = (int *) malloc(sizeof(int)*8); externally from the for (int j = 0; j < size; j++) loop let the code works. So why this allocation problem occurs when declared just like the above code and what's the best way to solve it?
I wrote a function that sorts an array of strings by their length
void lenSort(char sen[][NAME_LENGTH], int len)
{
int i = 0, j = 0, k = 0;
char tmp[NAME_LENGTH] = {0};
for(i = 0; i < len - 1; i++)
{
for(j = 0; j < len - i - 1; j++)
{
if(strlen(sen[j]) > strlen(sen[j+1]))
{
strncpy(tmp, sen[j], strlen(sen[j]));
for(k = 0; k < strlen(sen[j]); k++)
{
sen[j][k] = 0;
}
strncpy(sen[j], sen[j+1], strlen(sen[j+1]));
strncpy(sen[j+1], tmp, strlen(tmp));
}
}
}
}
The array I pass is: {"12345", "123", "123456", "12", "1234", "1234", "1234567", "123", "1", "12345"}
For some reason when I copy sen[j+1] into sen[j] I get excess characters, I thought that that's becuase sen[j] is longer, but I reset it before copying and it still happens and I don't have any clue why..
If you want to sort strings based on their length only then inner below for loop is not required though it may serving some other purpose
for(k = 0; k < strlen(sen[j]); k++)
{
sen[j][k] = 0;
}
here is the my solution. use strcpy() instead of strncpy() because strings copied using strncpy() are not null terminated. from the man page of strncpy
Warning: If there is no null byte among the first n bytes
of src, the string placed in dest will not be null-terminated.
void lenSort(char sen[][NAME_LENGTH], int len)
{
int i = 0, j = 0, k = 0;
char tmp[NAME_LENGTH] = {0};
for(i = 0; i < len - 1; i++)
{
for(j = 0; j < len - i - 1; j++)
{
if(strlen(sen[j]) > strlen(sen[j+1]))
{
strcpy(tmp, sen[j]);
strcpy(sen[j], sen[j+1]);
strcpy(sen[j+1], tmp);
}
}
}
}
I have to make a program that sort strings (with exact length 7 chars) by using radix sort. I already made a function that sort each column separately. My problem is how to make the whole string move, not just one char. It's really problematic for me to see how should it work in C.
I made one array "char strings[3][8]" and "char output[3][8]" to get sorted 3 strings with exact 7 chars in each one. For example sorting these strings:
strcpy(strings[0], "kupbars");
strcpy(strings[1], "daparba");
strcpy(strings[2], "jykaxaw");
In output I get:
dakaaaa
juparbs
kypbxrw
Each column is sorted correctly but chars don't stick together. I tried many ways for 3 hours but nothing works.
My code looks like this:
void countingSort(char a[][8], char b[][8]) {
int c[123];
for (int pos = 6; pos >= 0; pos--) {
for (int i = 0; i < 123; i++)
c[i] = 0;
for (int i = 0; i < 3; i++)
c[(int)a[i][pos]]++;
for (int i = 1; i < 123; i++)
c[i] += c[i - 1];
for (int i = 2; i >= 0; i--) {
b[--c[(int)a[i][pos]]][pos] = a[i][pos];
}
}
}
(There are constants limiting string length etc. because it's easy to change it to variable - I just focused on getting this program work properly.)
Try changing the loop to move an entire string:
for (int i = 2; i >= 0; i--) {
int k = --c[(int)a[i][pos]];
for(int j = 0; j < 8; j++) {
b[k][j] = a[i][j];
}
}
You could do a circular list but it's a little overhead. I propose you to use memmove().
#include <string.h>
void array_move_forward(char array[3][8]) {
for (int i = 0; i < 3; i++) {
char tmp = array[i][6];
memmove(array[i] + 1, array[i], 6);
array[i][0] = tmp;
}
}
void array_move_rewind(char array[3][8]) {
for (int i = 0; i < 3; i++) {
char tmp = array[i][0];
memmove(array[i], array[i] + 1, 6);
array[i][6] = tmp;
}
}
A other solution would be to manipulate your string yourself and using a index, that indicate the first letter of your string.
{
char str[7];
int i = 0;
...
int j = i;
for (int k = 0; k < 7; k++) {
char tmp = str[j++ % 7];
}
}
With that you could rotate your string just with i++ or i--.
struct my_string_radix {
char str[7];
int begin;
}
i am writing a rail fence cipher algorithm in c for fun and to brush up on my C programming skills. i have it working well for smallish input phrases, but it gets garbled for some reason when the input phrase is large.
here is the code: (sorry, i couldnt reduce it to a SSCCE, i dont know which part of the algorithm is causing the problem)
#include<stdio.h>
#include<string.h>
#include <stdlib.h>
/* function to append a char to a char array */
void append(char* s, char c)
{
int len = strlen(s);
s[len] = c;
s[len+1] = '\0';
}
int main(void)
{
int num_rails;
for (num_rails = 2; num_rails < 6; num_rails++)
{
char* message = "therailfencecipheristrickyespeciallywhentheinputisverylongabcdefghijklmnopqrstuvwxyzblerpblorp";
int word_len = strlen(message);
char* lines[num_rails];
char* rails[num_rails];
int len_rails[num_rails];
memset(len_rails, 0, num_rails*sizeof(int));
int i,j,k,mod;
int repeats;
int period = (2*num_rails) - 2;
printf("%d characters, %d rails:\n", word_len, num_rails);
printf("\nplaintext: %s\n", message);
/* encryption */
for (i = 0; i < num_rails; i++)
{
if ((lines[i] = malloc(sizeof(char))) == NULL)
{
printf("\nUnable to allocate memory.\n");
return EXIT_FAILURE;
}
}
for (repeats = 0; repeats < ((word_len/period)+1); repeats++)
{
if (repeats*period < word_len)
append(lines[0], message[repeats*period]);
for (j = 1; j < period/2; j++)
{
if ((j + (repeats*period)) < word_len)
append(lines[j], message[j + (repeats*period)]);
if ((((repeats+1)*period) - j) < word_len)
append(lines[j], message[((repeats+1)*period) - j]);
}
if (((period/2) + (repeats*period)) < word_len)
append(lines[j], message[(period/2)+(repeats*period)]);
}
char encrypted[word_len];
strcpy(encrypted,lines[0]);
for (i = 1; i < num_rails; i++)
strcat(encrypted, lines[i]);
printf("\nciphertext: %s\n", encrypted);
/* decryption */
for (i = 0; i < num_rails; i++)
{
if ((rails[i] = malloc(sizeof(int) * 40)) == NULL)
{
printf("\nUnable to allocate memory.\n");
return EXIT_FAILURE;
}
}
mod = word_len % period;
len_rails[0] = word_len / period;
len_rails[num_rails-1] = len_rails[0];
for (i = 1; i < num_rails - 1; i++)
len_rails[i] = len_rails[0] * 2;
for (i = 0; i < mod && i < num_rails; i++)
{
len_rails[i]++;
}
for (j = i-2; i < mod && j > -1; j--)
{
len_rails[j]++;
i++;
}
printf("\nrail lengths:");
for (i = 0; i < num_rails; i++)
printf(" %d", len_rails[i]);
putchar('\n');
k = 0;
for (i = 0; i < num_rails; i++)
{
for (j = 0; j < len_rails[i]; j++)
{
append(rails[i], encrypted[k++]);
}
}
char deciphered[word_len];
strcpy(deciphered, "");
for (i = 0; i < ((word_len/period)+1); i++)
{
if (rails[0][i])
append(deciphered, rails[0][i]);
for (j = 1; j < num_rails-1; j++)
{
if (rails[j][i*2])
append(deciphered, rails[j][i*2]);
}
if (rails[num_rails-1][i])
append(deciphered, rails[num_rails-1][i]);
for (j = num_rails-2; j > 0; j--)
{
if (rails[j][(i*2)+1])
append(deciphered, rails[j][(i*2)+1]);
}
}
printf("\ndeciphered: %s\n", deciphered);
printf("==========================================\n");
}
}
it should compile and run fine so you can test it.
it is supposed to print the plain text, then encipher it and print that, then decipher the enciphered text back to plain text and print that for 2, 3, 4, 5 rails but it should work for any number of rails.
the problem is that the output gets garbled if the input variable "message" gets over a certain size for different numbers of rails.
eg.
2 rails becomes garbled at 63 characters
3 rails becomes garbled at 64 characters
4 rails becomes garbled at 95 characters
5 rails becomes garbled at 126 characters
etc.
the closest i have been able to come to working out what is wrong is that whenever any value for len_rails[] exceeds 31 the output gets garbled for that amount of rails..
does anyone have any idea why this would be? is it to do with how i am allocating memory? its been a while since i did any C programming and my memory handling is a bit rusty.
any help would be greatly appreciated..
On this line:
if ((lines[i] = malloc(sizeof(char))) == NULL)
you are only allocating memory for a single char, but then try to use the buffer for storing much more than one char of data. Multiply sizeof(char) (which is, by the way, always 1) by the number of chars you are planning to store in the array.
Remember to free() the memory just before the end.
It crashes with a debug error and says stack around variable 'code' was corrupted. This is code for a hamming code lab I am doing. The input file is just a bunch of 1's and 0's on the same line. Why is it crashing?
void processFile(FILE* read, char* InMessage) {
int i = 0, count = 0;
for (i = 0; !feof(read); i++) {
InMessage[i] = fgetc(read);
count++;
}
InMessage[count] = '\0';
}
void hammingCode(char* InMessage) {
int len = strlen(InMessage), i = 0, j = 0;
char code[12], temp[1000];
temp[0] = '\0';
for (i = 0, j = 0; i < len; i++, j++) {
code[j] = InMessage[i];
if (j == 10) {
j = 0;
decode(code);
code[11] = '\0';
strcat_s(temp, sizeof(char)*1000, code);
}
}
strcpy_s(InMessage, sizeof(char)*1000, temp);
}
void decode(char* codeWord) {
int i = 0, j = 0, parity[4] = {0}, diffParity[4] = {0}, twoPower = 0, readNSkip = 0, bitSum = 0;
for (i = 0; i < 4; i++) {
twoPower = (int)pow((double)2, i);
for (j = twoPower; j <= 12; j++) {
if (readNSkip <= twoPower) {
if (j != twoPower) {
parity[i] += codeWord[j-2] - 48;
}
readNSkip++;
}
else {
if (readNSkip == twoPower*2)
readNSkip = 0;
readNSkip++;
}
}
if (parity[i] % 2 == 0)
parity[i] = 0;
else
parity[i] = 1;
if ((codeWord[twoPower-1] - 48) != parity[i])
diffParity[i] = 1;
}
for (i = 0; i < 4; i++) {
twoPower = (int)pow((double)2, i);
bitSum += diffParity[i]*twoPower;
}
codeWord[bitSum] = !codeWord[bitSum];
}
There's two problems I see here:
It looks to me like you are calculating the size of the InMessage buffer incorrectly in your hammingCode function:
int len = strlen(InMessage), i = 0, j = 0;
The strlen function determines the length of the string by finding the position of the first null terminator. If InMessage is not cleared, then this could give you some strange lengths as it will contain a random sequence of bytes. Conversely, if you have cleared the buffer then len will be 0.
To overcome this problem, it is better for the caller to provide the size of the buffer:
int hammingCode (char *InMessage, size_t messageSize)
And use messageSize in place of len.
It's advisable to use this same strategy for your other two functions as well as currently there is a chance of overflowing the provided buffers.
Following on from the previous problem, it may be that the decode function is writing outside the bounds of the buffer. Providing the length of the buffer to decode and adding the appropriate checks to ensure the function does not write outside the given bounds would be a good idea.