简体   繁体   中英

web.crypto encryption c# decryption

I'm trying to do:

  1. encrypt text using web.crypto,
  2. decrypt text using AesCryptoServiceProvider I didn't get any exceptions in my code, but the decryption doesn't match the plain text that i've encrypted

the plaintext bytes after decyption are the same, but the encoding to string doesn't work

I'm using random iv, the key and the plaintext are constant.

function cryptoSys(plaintext,KeyString){
        var iVec=window.crypto.getRandomValues(new Uint8Array(16));                        
        var encryptSuccessFunc=(encrypt)=> { AfterEncrypt(BytearrayToString(iVec),arraybufferTostring(encrypt));}
        var ImportKeySuccessFunc= (keyObj)=>{                  
                                  window.crypto.subtle.encrypt(                
                                   {name:"AES-CBC", iv:iVec},
                                   keyObj,
                                  StringToByteArray(plaintext)
                                   ).then(encryptSuccessFunc);           

         window.crypto.subtle.importKey(
            "raw", 
            StringToByteArray(KeyString),
            {name:"AES-CBC", length:128},
            true,
            ["encrypt","decrypt"]
            ).then(ImportKeySuccessFunc);
}

After that I'm sending the iVec, ciphertext using json

 function AfterEncrypt(iVec,ciphertext)
    {            
        var plaintext="String to Encrypt";
        if(iVec==null)
            return;
        var send2server= {"ciphertext":ciphertext,
            "iVec":iVec,
            "plaintext":plaintext};            
        var objectDataString = JSON.stringify(send2server);            
        sendJSONtoserver(objectDataString,"getDelayedBid");                  
    }

I'm using the following utility functions :

    function StringToByteArray(strString) {            

        var byteArray = new Uint8Array(strString.length);
        for (var i=0; i<strString.length; i++) {
            byteArray[i] = strString.charCodeAt(i);
        }
        return byteArray;
    }
    function BytearrayToString(arrayBuffer) {            
        var strString = "";                        
        for (var i=0; i<arrayBuffer.byteLength; i++) {                
            strString += String.fromCharCode(arrayBuffer[i]);
        }
        return strString;
    }
     function arraybufferTostring(buf) {
        return String.fromCharCode.apply(null, new Uint8Array(buf));
    }

server side accepts the keys, and suppose to decrypt:

public string DecryptCipher(Encoding u16, string cipherText, string key,string iVec)
    {
        byte[] ciphertextBytes = clearZeros(u16.GetBytes(cipherText)); 
        AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
        aes.BlockSize = 128;
        aes.KeySize = 128; //minimun key length
        aes.Key = clearZeros(u16.GetBytes(key)); 
        aes.IV = clearZeros(u16.GetBytes(iVec));
        aes.Padding = PaddingMode.PKCS7;
        aes.Mode = CipherMode.CBC;
        ICryptoTransform cryptoTrans = aes.CreateDecryptor(aes.Key, aes.IV);
        byte[] plaintextBytes = cryptoTrans.TransformFinalBlock(ciphertextBytes, 0, ciphertextBytes.Length);
        cryptoTrans.Dispose();
        return Convert.ToBase64String(plaintextBytes);
    }

I've got this utility function as well:

private byte [] clearZeros(byte [] bytearray)
    {
        byte[] ans = new byte[bytearray.Length / 2];
        for (int i = 0; i < bytearray.Length / 2; i++)
            ans[i] = bytearray[2 * i];
        return ans;
    }

I'm getting the paramters from anthor function:

public ActionResult getDelayedBid([FromBody] DelayedSubmission delaySub)
    {
        if (delaySub.ciphertext == null)
            return Json("Failure", JsonRequestBehavior.AllowGet);
        Encoding u16LE = Encoding.Unicode;        
        String decrypetedMessageLE = new Encryption().DecryptCipher(u16LE, delaySub.ciphertext,  getKeyFromDB(), delaySub.iVec);                
        if (decrypetedMessageLE.Equals(delaySub.plaintext) )
            {
                return Json("Success", JsonRequestBehavior.AllowGet);
            }
        return Json("Failure", JsonRequestBehavior.AllowGet);
}

I've used wrong Ecoding, instand of

Convert.ToBase64String(plaintextBytes);

I should've used

Encoding.ASCII.GetString(plaintextBytes);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM