재우니의 블로그

 

ASP.NET MVC : CBC, Pkcs7 암호화 및 복호화 라이브러리 함수

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;

namespace WebApp48.Helpers
{
    public static class Utility
    {
        public static string DecryptStringAES(string cipherText)
        {

            var keybytes = Encoding.UTF8.GetBytes("8080808080808080");
            var iv = Encoding.UTF8.GetBytes("8080808080808080");

            var encrypted = Convert.FromBase64String(cipherText);
            var decriptedFromJavascript = DecryptStringFromBytes(encrypted, keybytes, iv);
            return string.Format(decriptedFromJavascript);
        }

        private static string DecryptStringFromBytes(byte[] cipherText, byte[] key, byte[] iv)
        {
            // Check arguments.
            if (cipherText == null || cipherText.Length <= 0)
            {
                throw new ArgumentNullException("cipherText");
            }
            if (key == null || key.Length <= 0)
            {
                throw new ArgumentNullException("key");
            }
            if (iv == null || iv.Length <= 0)
            {
                throw new ArgumentNullException("key");
            }

            // Declare the string used to hold
            // the decrypted text.
            string plaintext = null;

            // Create an RijndaelManaged object
            // with the specified key and IV.
            using (var rijAlg = new RijndaelManaged())
            {
                //Settings
                rijAlg.Mode = CipherMode.CBC;
                rijAlg.Padding = PaddingMode.PKCS7;
                rijAlg.FeedbackSize = 128;

                rijAlg.Key = key;
                rijAlg.IV = iv;

                // Create a decrytor to perform the stream transform.
                var decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);
                try
                {
                    // Create the streams used for decryption.
                    using (var msDecrypt = new MemoryStream(cipherText))
                    {
                        using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                        {

                            using (var srDecrypt = new StreamReader(csDecrypt))
                            {
                                // Read the decrypted bytes from the decrypting stream
                                // and place them in a string.
                                plaintext = srDecrypt.ReadToEnd();

                            }

                        }
                    }
                }
                catch
                {
                    plaintext = "keyError";
                }
            }

            return plaintext;
        }

        public static byte[] EncryptStringToBytes(string plainText, byte[] key, byte[] iv)
        {
            // Check arguments.
            if (plainText == null || plainText.Length <= 0)
            {
                throw new ArgumentNullException("plainText");
            }
            if (key == null || key.Length <= 0)
            {
                throw new ArgumentNullException("key");
            }
            if (iv == null || iv.Length <= 0)
            {
                throw new ArgumentNullException("key");
            }
            byte[] encrypted;
            // Create a RijndaelManaged object
            // with the specified key and IV.
            using (var rijAlg = new RijndaelManaged())
            {
                rijAlg.Mode = CipherMode.CBC;
                rijAlg.Padding = PaddingMode.PKCS7;
                rijAlg.FeedbackSize = 128;

                rijAlg.Key = key;
                rijAlg.IV = iv;

                // Create a decrytor to perform the stream transform.
                var encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);

                // Create the streams used for encryption.
                using (var msEncrypt = new MemoryStream())
                {
                    using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (var swEncrypt = new StreamWriter(csEncrypt))
                        {
                            //Write all data to the stream.
                            swEncrypt.Write(plainText);
                        }
                        encrypted = msEncrypt.ToArray();
                    }
                }
            }

            // Return the encrypted bytes from the memory stream.
            return encrypted;
        }
    }
}

 

javascript 에서 CBC, Pkcs7 으로 암호화 처리

 

중요한것은 "https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/aes.js" 를 활용하여 암호화작업을 스크립트 단에서 작업이 가능하다는 점입니다.

 

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/aes.js"></script>
<script type="text/javascript">
    $(function () {
        $("#btnSave").click(function () {

            var enc1 = '==냠냠?test=&jcop=test&동해물과 + + 백두산이 마르고 닳도록 abcdefghijh ~!@@#$%^&*()_+|<>?"';

            var key = CryptoJS.enc.Utf8.parse('8080808080808080');
            var iv = CryptoJS.enc.Utf8.parse('8080808080808080');
            var encryptedlogin = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(enc1), key,
                { keySize: 128 / 8, iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 });
            var enc = encryptedlogin;
            console.log(enc);


            $.ajax({
                type: "POST",
                url: '@Url.Action("GetData")',
                data: JSON.stringify({enc: '' + enc + ''}),
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                success: function () {
                    alert("Data has been added successfully.");
                },
                error: function () {
                    alert("Error while inserting data");
                }
            });
            return false;
        });
    });
</script>
<h2>Index</h2>
<input type="button" name="Save" value="Save" id="btnSave" />

 

jQuery 의 ajax 통신에 대한 backend 단 기술 부분 입니다.

public JsonResult GetData(string enc)
{
  var DecryptVal = Utility.DecryptStringAES(enc);            
  return Json(DecryptVal, JsonRequestBehavior.AllowGet);
}

 

끝~

 

 

asp.net mvc 의 c# 에서 CBC, Pkcs7 암호화 및 복호화

 

스크립트의 라이브러리 도움없이 backend 단에서도 암복호화 가능합니다. 

public ActionResult Index()
{
  var rawData = "==냠냠?test=&jcop=test&동해물과 + + 백두산이 마르고 닳도록 abcdefghijh ~!@#$%^&*()_+|<>?";

  var key = Encoding.UTF8.GetBytes("8080808080808080");
  var iv = Encoding.UTF8.GetBytes("8080808080808080");
  var encByte = Utility.EncryptStringToBytes(rawData, key, iv);
  var encString = Convert.ToBase64String(encByte, 0, encByte.Length);
  var decryptVal = Utility.DecryptStringAES(encString);

  return View();
}

 

 

참고 사이트

 

1> Encrypt in javascript and pass it into Ajax call and decrypt in MVC Controller using AES Algorithm

https://www.coreprogramm.com/2021/01/encrypt-in-javascript-pass-data-in-ajax-call-decrypt-controller.html

 

Encrypt in javascript and pass it into Ajax call and decrypt in MVC Controller using AES Algorithm

Encrypt in javascript and pass it into Ajax call and decrypt in MVC Controller using AES Algorithm

www.coreprogramm.com

 

2> c# - .NET에서 문자열을 암호화하는 방법은 무엇입니까?

https://pythonq.com/so/c%23/424144

 

c# - .NET에서 문자열을 암호화하는 방법은 무엇입니까? [복제] - IT 툴 넷

This question already has answers here: Encrypt and decrypt a string in C#?                                                              (28 답변)                        

pythonq.com

 

3> CryptoJS decrypt object

https://stackoverflow.com/a/50328007

 

CryptoJS decrypt object

I need to decrypt something encrypted with CryptoJS. I have the function used to encrypt, the structure of the object encrypted and data used to encrypt to encrypt but i need to know some values of...

stackoverflow.com

 

 

 


아래 사이트도 많이 도움이 될겁니다. 중복된 블로그 글 같네요.. ~ ^^;;

C# 의 AES/CBC/PKCS5Padding 으로 암복호화 하기

 

C# 의 AES/CBC/PKCS5Padding 으로 암복호화 하기

AES/CBC/PKCS5Padding Encryption/Decryption in C# Zeb Sadiq | AES/CBC/PKCS5Padding Encryption/Decryption in C# by zebsadiq 1. 7월 2013 13:33 I’ve recently been asked to write some code to decrypt s..

aspdotnet.tistory.com