First Commit
This commit is contained in:
@@ -0,0 +1,8 @@
|
||||
namespace ADS.Apis.Gps.Infrastructure.Crypto;
|
||||
|
||||
public sealed class LegacyCryptoOptions
|
||||
{
|
||||
public string Mode { get; set; } = "AES"; // "DES" o "AES"
|
||||
public string Key { get; set; } = "";
|
||||
public string IV { get; set; } = ""; // Base64
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using ADS.Apis.Gps.Application.Common.Crypto;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace ADS.Apis.Gps.Infrastructure.Crypto;
|
||||
|
||||
public sealed class LegacyPasswordEncryptor : ILegacyPasswordEncryptor
|
||||
{
|
||||
private readonly LegacyCryptoOptions _opt;
|
||||
|
||||
public LegacyPasswordEncryptor(IOptions<LegacyCryptoOptions> opt)
|
||||
=> _opt = opt.Value;
|
||||
|
||||
public string Encrypt(string plainText)
|
||||
{
|
||||
if (string.IsNullOrEmpty(plainText)) return string.Empty;
|
||||
|
||||
var mode = (_opt.Mode ?? "AES").Trim().ToUpperInvariant();
|
||||
var iv = Convert.FromBase64String(_opt.IV ?? "");
|
||||
|
||||
return mode switch
|
||||
{
|
||||
"DES" => EncryptDesBase64(plainText, _opt.Key, iv),
|
||||
"AES" => EncryptAesBase64(plainText, _opt.Key, iv),
|
||||
_ => throw new InvalidOperationException($"Unsupported LegacyCrypto.Mode: {_opt.Mode}")
|
||||
};
|
||||
}
|
||||
|
||||
private static string EncryptDesBase64(string plainText, string keySource, byte[] iv8)
|
||||
{
|
||||
if (iv8.Length != 8) throw new ArgumentException("DES IV must be 8 bytes.", nameof(iv8));
|
||||
|
||||
var key8 = Encoding.UTF8.GetBytes((keySource ?? string.Empty).PadRight(8).Substring(0, 8));
|
||||
|
||||
using var des = new DESCryptoServiceProvider
|
||||
{
|
||||
Mode = CipherMode.CBC,
|
||||
Padding = PaddingMode.PKCS7,
|
||||
Key = key8,
|
||||
IV = iv8
|
||||
};
|
||||
|
||||
var input = Encoding.UTF8.GetBytes(plainText);
|
||||
using var encryptor = des.CreateEncryptor(des.Key, des.IV);
|
||||
var cipher = encryptor.TransformFinalBlock(input, 0, input.Length);
|
||||
|
||||
return Convert.ToBase64String(cipher);
|
||||
}
|
||||
|
||||
private static string EncryptAesBase64(string plainText, string keySource, byte[] iv16)
|
||||
{
|
||||
if (iv16.Length != 16) throw new ArgumentException("AES IV must be 16 bytes.", nameof(iv16));
|
||||
|
||||
var key32 = Encoding.UTF8.GetBytes((keySource ?? string.Empty).PadRight(32).Substring(0, 32));
|
||||
|
||||
using var aes = Aes.Create();
|
||||
aes.Mode = CipherMode.CBC;
|
||||
aes.Padding = PaddingMode.PKCS7;
|
||||
aes.Key = key32;
|
||||
aes.IV = iv16;
|
||||
|
||||
var input = Encoding.UTF8.GetBytes(plainText);
|
||||
using var encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
|
||||
var cipher = encryptor.TransformFinalBlock(input, 0, input.Length);
|
||||
|
||||
return Convert.ToBase64String(cipher);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user