클리엘
CLIEL LAB
클리엘
전체 방문자
오늘
어제
  • 분류 전체보기 (515)
    • Mobile (47)
      • Kotlin (47)
    • Web (84)
      • NestJS (9)
      • HTML5 & CSS3 (38)
      • Javascript (20)
      • TypeScript (6)
      • JQuery (11)
    • .NET (302)
      • C# (85)
      • ASP.NET (67)
      • Windows API for .NET (128)
    • Server (53)
      • SQL Server (10)
      • MariaDB (18)
      • Windows Server (6)
      • node.js (19)
    • System (12)
      • 작업LOG (12)
    • Review (11)
    • ETC (6)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

  • 블로그 정리

인기 글

태그

  • Kotlin
  • node.js
  • exception
  • 변수
  • HTML5
  • android
  • Entity Framework
  • jQuery
  • LINQ
  • JavaScript
  • CSS3
  • c#
  • asp.net core
  • MariaDB
  • NestJS
  • android studio
  • ASP.NET
  • .NET
  • Windows API
  • asp.net core web api

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
클리엘

CLIEL LAB

.NET/ASP.NET

[ASP.NET Core] 암호화 사용하기(DataProtection)

2021. 11. 7. 02:31
728x90

1. Class Library형식의 Project를 생성하고 'Microsoft.AspNetCore.DataProtection' 이름의 Nuget package를 설치합니다.

 

2. project에 다음과 같은 class를 추가해 사용할 암호화 algorithm을 지정합니다. 예제에서는 myWebLibrary라는 이름의 project를 생성하였습니다.

using Microsoft.Extensions.DependencyInjection;
using System;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel;

namespace myWebLibrary
{
    public class Utils
    {
        public static void SetDataProtection(IServiceCollection services, string keyPath, string appName)
        {
            var builder = services.AddDataProtection().PersistKeysToFileSystem(new System.IO.DirectoryInfo(keyPath)).SetDefaultKeyLifetime(TimeSpan.FromDays(7)).SetApplicationName(appName);

            builder.UseCryptographicAlgorithms(
                new AuthenticatedEncryptorConfiguration()
                {
                    EncryptionAlgorithm = Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.EncryptionAlgorithm.AES_256_CBC,
                    ValidationAlgorithm = Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ValidationAlgorithm.HMACSHA512
                });

            //혹은 또 다른 암호화 Algorithm사용
            //builder.UseCustomCryptographicAlgorithms(
            //            new ManagedAuthenticatedEncryptorConfiguration()
            //            {
            //                EncryptionAlgorithmType = typeof(System.Security.Cryptography.Aes),
            //                EncryptionAlgorithmKeySize = 256,
            //                ValidationAlgorithmType = typeof(HMACSHA512)
            //            });
        }
    }
}

PersistKeysToFileSystem() method는 생성된 key를 저장할 경로를 지정하며 SetDefaultKeyLifetime()은 key수명관리일을 지정하는 method입니다. 만약 SetDefaultKeyLifetime() method를 사용하지 않으면 기본 90일이 적용됩니다.

 

SetApplicationName() method는 app간에app 간에 보호된 payload를 공유하고자 하는 것입니다. 해당 method를 사용하지 않아도 되지만 같은 서로 다른 app 간에 같은 PersistKeysToFileSystem()의 key경로를 공유한다고 하더라도 암호화를 공유할 수 없습니다.

 

예제에서는 UseCryptographicAlgorithms을 사용하도록 하였으며 기타 UseCustomCryptographicAlgorithms을 사용해 CngCbcAuthenticatedEncryptorConfiguration나 ManagedAuthenticatedEncryptorConfiguration등을 사용할 수 있습니다.

 

3. 2에서 만든 project를 참조하여 ConfigureServices에 service등록을 설정합니다.

Utils.SetDataProtection(services, @"C:\inetpub\wwwroot\key", "myWeb");

참고로 좀더 빠르게 적용하려면 1에서 처럼 별도의 project나 class를 생성하지 않고 곧바로 암호화 Algorithms service를 등록해 줄 수도 있습니다.

 

4. 암호화를 사용할 Controller에서 생성자 주입방식의 의존성해결자를 통해 DataProvider의 instance를 가져올 수 있도록 합니다.

private readonly ILogger<HomeController> _logger;
private IDataProtector _IDataProtection;

public HomeController(ILogger<HomeController> logger, IDataProtectionProvider provider)
{
    _logger = logger;
    _IDataProtection = provider.CreateProtector("protect");
}

5. 암호화는 Protect()를 복호화에는 Unprotect() method를 사용합니다.

public IActionResult Index()
{
    //var r = _IData.GetUser("abc");

    string en = _IDataProtection.Protect("abcdefg");
    string de = _IDataProtection.Unprotect(en);

    TempData["de"] = de;

    return View();
}
728x90
저작자표시 비영리 변경금지 (새창열림)

'.NET > ASP.NET' 카테고리의 다른 글

[ASP.NET Core] Logging  (0) 2021.11.13
[ASP.NET Core] Claim 인증과 권한  (0) 2021.11.11
[ASP.NET Core] SQL 사용하기  (0) 2021.11.05
[ASP.NET Core] Entity Framework Core (Code-First)  (0) 2021.11.02
[ASP.NET Core] 의존성 주입(Dependency Injection)  (0) 2021.11.01
    '.NET/ASP.NET' 카테고리의 다른 글
    • [ASP.NET Core] Logging
    • [ASP.NET Core] Claim 인증과 권한
    • [ASP.NET Core] SQL 사용하기
    • [ASP.NET Core] Entity Framework Core (Code-First)
    클리엘
    클리엘
    누구냐 넌?

    티스토리툴바