2017-05-07 125 views
-1

我正在研究一個非常簡單的加密程序。我從輸入消息,密碼,輸出和2個按鈕開始。解密加密郵件(我加密)

<input type="text" id="message"></input><br> 
<input type="text" id="password"></input> 
<p id="encrypted"></p> 

<button class="trans" id="button-encrypt">encrypt!</button> 
<button class="trans" id="button-decrypt">decrypt!</button> 

在按下按鈕加密,出現這種情況:

  1. 捕獲的口令字符串,並把它變成一個數
  2. 數目被用來生成26個字母的陣列
  3. 將消息中的字母映射到數組(稱爲mapArray)

步驟3看起來像這樣:

var mapToMapArray = { 
     a: mapArray[0], b: mapArray[1], c: mapArray[2]... 
    }; 

    //this code courtesy of another user from here on stackoverflow 
    encryptedEl.innerHTML = messageEl.split("").map((letter) => mapToMapArray[letter] || letter).join(""); 

基本上,當我點擊加密按鈕時,輸出是亂碼。這個亂碼根據我輸入的密碼而有所不同。例如,如果我輸入'hank'作爲消息,輸入'abcde'作爲密碼,則輸出爲'afbz'。如果我輸入'hank'作爲信息,'pine'輸入密碼,則輸出'yvza'。

問:

現在,我想要的是相反的過程,當我打的解密按鈕。如果我輸入密碼爲'pine'的'yvza',我想'hank'是輸出。我不知道該怎麼做。無論如何,我認爲自己是初學者,所以如果解決方案很明顯,我表示歉意。

+0

查找密碼陣列(array.indexOf)加密信件的位置。如果位置爲0,則未加密的字母爲a,1 = b,依此類推。 – James

+0

類似'unencryptedEl.innerHTML = encryptedEl.split(「」)。map(letter => String.fromCharCode(mapArray.indexOf(letter)+ 65))。join(「」);''''(未測試) – James

+0

我剛試過a:String.fromCharCode(97 + mapArray.indexOf(「a」))在mapToMapArray中並且它工作了(對於字母'a')。我會在map()方法中嘗試它,但我認爲這正是我一直在尋找的解決方案 – Jozurcrunch

回答

-1

var message = document.getElementById("message"), 
 
    password = document.getElementById("password"), 
 
    encrypted = document.getElementById("encrypted"), 
 
    decrypted = document.getElementById("decrypted"), 
 
    output = document.getElementById("output"); 
 
function loop(array, callback) { 
 
    var len = array.length, 
 
     index; 
 
    for (index = len - 1; index >= 0; index -= 1) { 
 
     callback.call(index, array[index], index); 
 
    } 
 
} 
 
encrypted.addEventListener("click", function(){ 
 
    if(message.value!="" && password.value!=""){ 
 
    var passi = 0; 
 
    var ec = message.value.replace(/[\w|\W]/g, function(a){ 
 
     var pv = password.value[passi].charCodeAt(0); 
 
     passi+=1; 
 
     if(passi>=password.value.length){ 
 
     passi=0; 
 
     } 
 
     var av = a.charCodeAt(0); 
 
     return String.fromCharCode(pv+av); 
 
    }); 
 
    output.value = btoa(ec); 
 
    } 
 
}); 
 
decrypted.addEventListener("click", function(){ 
 
    if(output.value!="" && password.value!=""){ 
 
    var passi = 0; 
 
    var dc = atob(output.value).replace(/[\w|\W]/g, function(a){ 
 
     var pv = password.value[passi].charCodeAt(0); 
 
     passi+=1; 
 
     if(passi>=password.value.length){ 
 
     passi=0; 
 
     } 
 
     var av = a.charCodeAt(0); 
 
     return String.fromCharCode(av-pv); 
 
    }); 
 
    output.value = dc; 
 
    } 
 
});
<input placeholder="message" id="message" value="abcdefg"> 
 
<input placeholder="password" id="password" value="123"> 
 
<br> 
 
<button id="encrypted">encrypted</button> 
 
<button id="decrypted">decrypted</button> 
 
<br> 
 
<input placeholder="output" id="output">