NEWS

[C#] Mã hóa và giải mã Data Protection API trên winform

[C#] Mã hóa và giải mã Data Protection API trên winform
Đăng bởi: Thảo Meo - Lượt xem: 2981 23:36:04, 25/05/2022DEVEXPRESS   In bài viết

Xin chào các bạn, bài viết hôm nay mình sẻ tiếp tục hướng dẫn các bạn mã hóa và giải mã sử dụng Data Protection API trên Windows C#, Winform.

[C#] Encrypt - Decrypt DPAPI in Winform

DPAPI là mã hóa dựa trên tài khoản Windows: CurrentUser hoặc Local Machine, được Microsoft giới thiệu từ năm 2000

Giao diện demo ứng dụng:

DPAPI_encrypt_decrypt

Full source code mã hóa và giải mã C#:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DPAPEncrypt
{
    public partial class Form1 : Form
    {
        readonly byte[] entropy = { 1, 2, 3, 4, 5, 6 }; //the entropy

        public Form1()
        {
            InitializeComponent();
        }

        private void btnEncrypt_Click(object sender, EventArgs e)
        {
            var txt = Encrypt(txtOriginText.Text);
            txtEncryptText.Text = txt;
        }

        private void btnDecrypt_Click(object sender, EventArgs e)
        {
            var txt = Decrypt(txtEncryptText.Text);
            txtDecryptText.Text = txt;
        }

        private string Encrypt(string text)
        {           
            byte[] originalText = Encoding.Unicode.GetBytes(text);         
            byte[] encryptedText = ProtectedData.Protect(originalText, entropy, DataProtectionScope.CurrentUser);         
            return Convert.ToBase64String(encryptedText);
        }

        private string Decrypt(string text)
        {          
            byte[] encryptedText = Convert.FromBase64String(text);           
            byte[] originalText = ProtectedData.Unprotect(encryptedText, entropy, DataProtectionScope.CurrentUser);          
            return Encoding.Unicode.GetString(originalText);
        }
    }
}

Các bạn có thể thay đổi:

DataProtectionScope.CurrentUser => DataProtectionScope.LocalMachine

Thanks for watching!

DOWNLOAD SOURCE

 

THÔNG TIN TÁC GIẢ

BÀI VIẾT LIÊN QUAN

[C#] Mã hóa và giải mã Data Protection API trên winform
Đăng bởi: Thảo Meo - Lượt xem: 2981 23:36:04, 25/05/2022DEVEXPRESS   In bài viết

CÁC BÀI CÙNG CHỦ ĐỀ

Đọc tiếp
.