2015-04-29 28 views
0

我寫了一個小程序,用於加密和解密用戶給出的一些字符串。解密並加密循環中的字符串

加密功能正在工作!但現在我必須解密它。我的問題是我無法真正想象如何實現這一步。

這裏是我的加密代碼:

function encrypt(origin: string; cols: byte; fillChar: char): string; 
var 
    a, c, d, e, rest, restfill, langewort: integer; 
    temp1, temp2: string; 
begin 
    langewort := length(origin); 
    rest := length(origin) mod cols; 
    restfill := cols - rest; 

    if (rest = 0) then 
    restfill := cols - 1 
    else 
    begin 
    for c := 1 to restfill do 
    begin 
     origin := origin + fillChar; 
    end; 
    end; 

    temp1 := ''; 

    for d := 1 to cols do 
    begin 
    for e := 0 to restfill - 1 do 
    begin 
     temp1 := temp1 + origin[d + cols * e]; 
    end; 
    end; 
    encrypt := temp1; 
end; 

比方說我們用這個字符串Stringnum,加密之後,我們有這樣的:Snmtg $ RN $ IU $ 解密函數必須扭轉它和刪除fillChar。

我會先從:

function decrypt(origin: string; cols: byte; fillChar: char): string; 
var 
    a, c, d, e, rest, restfill, langewort: integer; 
    temp1, temp2: string; 
begin 
    langewort := length(origin); 
    rest := length(origin) mod cols; 
    restfill := cols - rest; 

    if (rest = 0) then 
    restfill := cols - 1 
    else 
    begin 
    for c := 1 to restfill do 
    begin 
     origin := origin + fillChar; 
    end; 
    end; 

    temp1 := ''; 

    for d := 1 to cols do 
    begin 
    for e := 0 to restfill - 1 do 
    begin 
     temp1 := temp1 + origin[d - cols * e]; //<- change made here ? 
    end; 
    end; 
    decrypt := temp1; 
end; 
+0

你試過了嗎?出了什麼問題?請準確地添加你想要做的事情,以及爲什麼你發佈的代碼不起作用,或者將解密函數標記爲僞代碼(如果是這樣的話)。 –

+2

解密方法的問題在於,其餘變量與加密函數中的變量不同,因爲它是根據原始字符串的長度計算的,原始字符串由於在加密過程中添加了更多字符而變得更大。所以你應該保留加密字符串中的一個字符來存儲原始字符串的長度。 – SilverWarior

+3

第一步是學習文本和二進制文件的區別 –

回答

1

,儘管有上面我的意見,這裏是一個普遍的幫手。您的加密本質上是爲了產生一個原始的字母,並且您使用字符串連接來綁定您以某種順序進行操作。如果你重新排列你的代碼有點像這樣

SetLength(Temp1, Length(Origin)); // or cheat with Temp1 := origin 


    for d := 1 to cols do 
    begin 
    for e := 0 to restfill - 1 do 
    begin 
     temp1[ (d-1) * restfill + e + 1] := origin[d + cols * e]; 
    end; 
    end; 

你基本上是做同樣的事情,但爲了不那麼重要和逆算法更加明顯

SetLength(Temp1, Length(Origin)); // or cheat with Temp1 := origin 


    for d := 1 to cols do 
    begin 
    for e := 0 to restfill - 1 do 
    begin 
     temp1[d + cols * e] := origin[ (d-1) * restfill + e + 1]; 
    end; 
    end; //(the meaning of temp1 and origin is reversed of course) 

這不填串'正確的順序',但這並不重要,因爲我們現在將字符串視爲一個char數組。

請注意,這是而不是解決您的原始代碼的根本問題。