اگر برنامههای ASP.NET Core را اجرا کرده باشید، عموما در ابتدای آن یک پیام محافظت نشده بودن کلیدهای سیستم DataProtection را لاگ میکند. برای رفع این مشکل میتوان این مراحل را طی کرد:
الف) نیاز به یک مجوز SSL داریم که دارای private key هم باشد.
برای این منظور سه دستور زیر را صادر کنید تا یک فایل pfx مناسب سیستم DataProtection تولید شود:
"C:\Program Files\Git\usr\bin\openssl.exe" genrsa -out private.key 2048 "C:\Program Files\Git\usr\bin\openssl.exe" req -new -x509 -key private.key -out publickey.cer -days 1398 "C:\Program Files\Git\usr\bin\openssl.exe" pkcs12 -export -out idp.pfx -inkey private.key -in publickey.cer
ب) خواندن فایل pfx در برنامه
روش خواندن فایلهای pfx به صورت زیر است:
private static X509Certificate2 loadCertificateFromFile(string filePath, string password) { // NOTE: // You should check out the identity of your application pool and make sure // that the `Load user profile` option is turned on, otherwise the crypto susbsystem won't work. // For decryption the certificate must be in the certificate store. It's a limitation of how EncryptedXml works. using (var store = new X509Store(StoreName.My, StoreLocation.CurrentUser)) { store.Open(OpenFlags.ReadWrite); store.Add(new X509Certificate2(filePath, password, X509KeyStorageFlags.Exportable)); } return new X509Certificate2( filePath, password, keyStorageFlags: X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable); }
ج) معرفی مجوز تولید شده به سیستم
دراینجا آخرین مرحله، ذکر متد ProtectKeysWithCertificate به همراه مجوزی است که تولید کردیم:
services .AddDataProtection() .SetDefaultKeyLifetime(...) .SetApplicationName(...) .ProtectKeysWithCertificate(loadCertificateFromFile("path ...", "123"));