我洗掉了重復的問題,這是最終修訂版。我有一個關于如何在 C 中使用字串密鑰解密解密字串的問題。我關于使用 int 密鑰進行加密和解密的基本資訊,但不知道如何處理字串密鑰。
我需要使用這些僅給定的資料撰寫下面的函式定義,并且注釋作為幫助撰寫函式的提示。
位運算子之一已用于使用加密密鑰中的所有字符(從左到右)一次加密一個字符。給定加密密鑰和 ent[] 加密文本,解密函式檢索原始文本并將其放在 det[] 中。
void decrypt(const char key[], const char ent[], char det[]);//fun prototype
char key[] = "Advanced C";
char ent[100] = ""├8023.)/<)423}2;}↑%>1(.4 8}??};2/}├<)<}↑3>/$-)423}<39}├8>/$-)423s";
ent[] 字串影像
char det[100];
遵循哪種演算法來處理字串鍵。在這種情況下,我需要從左到右使用 key[] 中的所有字符,但不知道用什么演算法來做到這一點。
我的第一次嘗試并沒有奏效
void decrypt(const char key[], const char ent[], char det[])
{
int i = 0;
while (ent[i] != '\0')
{
int j = 0;
while (key[j] != '\0')
{
det[i] = ent[i] ^ key[j];
j ;
i ;
if(!(*ent))
break;
}
}
}
uj5u.com熱心網友回復:
如果 XOR 是演算法,那么加密和解密可以簡化為:
#include <stdio.h>
#include <string.h>
void decrypt (const char key[], const char cipher[], char text[]) {
char XOR = 0;
while (*key) XOR ^= *key ;
strcpy (text, cipher); // buffer overflow chance
while (*text) *text ^= XOR;
}
void encrypt (const char key[], const char text[], char cipher[]) {
char XOR = 0;
while (*key) XOR ^= *key ;
strcpy (cipher, text); // buffer overflow chance
while (*cipher) *cipher ^= XOR;
}
int main () {
char key[] = "Advanced C";
char ent[100] = "";//├8023.)/<)423}2;}↑%>1(.4 8}??};2/}├<)<}↑3>/$-)423}<39}├8>/$-)423s";
char det[100] = "Demonstration of Exclusive OR for Data Encryption and Decryption.";
encrypt(key, det, ent);
printf ("Encrypted Text: [%s]\n", ent);
det[0] = '\0';
decrypt(key, ent, det);
printf ("Decrypted Text: [%s]\n", det);
return 0;
}
uj5u.com熱心網友回復:
(我的回答是我如何提出和回答家庭作業問題?記住。從對 OP 解釋的想法的一些反饋開始。)
“我應該在 key 中累積每個字符的 ASCII 碼嗎?”
是的,Eric Postpischl 嘗試過,結果有點奇怪但實際上可讀的輸出。
(這是我的想法,相信 Eric,我現在認為不太可能:
可能不會。我建議單獨使用每個字符。
即
- 在第一個加密文本字符上使用第一個密鑰字符,結果進入第一個解密文本字符
- 然后將第二個加密文本字符上的第二個密鑰字符轉換為第二個解密文本字符
)
“然后異或”
不一定。您的分配宣告“位運算子之一”,因此不一定是 XOR。但是,是的,XOR 對可逆加密最有意義,所以一定要先嘗試。
“或使用 >> 或 << 或究竟是什么”
我不會認為這些運算子屬于“按位”運算子。所以不,不太可能。
“在 key[] 結束時重新開始”
是的,這似乎是唯一可能的方法。
“但也沒有用”
如果您詳細說明出了什么問題,這將有所幫助。
但是我希望不累積密鑰可以解決您的問題。
請顯示您獲得的結果以及您嘗試過的內容的 MRE ( https://stackoverflow.com/help/minimal-reproducible-example )。
看到你的功能,看看
det[i] = ent[i] ^ key[j];
在內部回圈中,隨著 j 和常數 i 的變化,它將重復寫入det. 但只有最后一個有效果,只有最后一個關鍵字符被有效使用。
你打算積累但沒有。
考慮在內部回圈之外使用該行(或非常相似的東西),j為 0,然后在回圈內部做一些不同的事情,這讓所有關鍵字符都有影響。
(見 Erics 評論,它更詳細。)
看到修改后的功能,我懷疑
j ;
i ;
i在內回圈內遞增似乎很可疑。它很容易通過 . 的終止符ent和det.
請使用除錯器來觀察您的程式是否正常作業。
Looking at another update of your code, I wonder what you are trying to program there. I understand that what you want to do is "accumulate all characters of the key to one key, apply that one key to all input characters". There is a way to do that in nested loops, but I recommend to do the accumulating in one non-nested loop and in a second non-nested loop apply the accumulated key to each input character. I recommd to throw your current version of the inner loop away, indeed drop the whole concept of an innner loop an try again. Reading Erics comment it seems to be more than sufficiently detailed.
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/448241.html
