Skip to content

Commit c069d94

Browse files
committed
modify the EncryptToBase64StringAsync method to allow users specify IV key
1 parent eb59dfb commit c069d94

1 file changed

Lines changed: 17 additions & 9 deletions

File tree

src/SafeCrypt.Lib/Encryption/AesEncryption/Encrypting.cs

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -84,33 +84,41 @@ public static async Task<EncryptionData> EncryptToHexStringAsync(EncryptionParam
8484
/// <exception cref="FormatException">
8585
/// Thrown if the base64secretKey is not a valid Base64-encoded string.
8686
/// </exception>
87-
public static async Task<EncryptionData> EncryptToBase64StringAsync(string dataToBeEncrypted, string base64secretKey, CipherMode mode = CipherMode.CBC)
87+
public static async Task<EncryptionData> EncryptToBase64StringAsync(EncryptionParameters param, CipherMode mode = CipherMode.CBC)
8888
{
8989
// validate is base64
90-
if (!Validators.IsBase64String(base64secretKey))
90+
var responseData = new EncryptionData();
91+
92+
var parameterValidation = ValidateEncryptionParameters(param);
93+
94+
if (parameterValidation.HasError)
9195
{
92-
return null;
96+
return parameterValidation;
9397
}
9498

95-
NullChecks(data: dataToBeEncrypted, base64secretKey);
99+
if (!Validators.IsBase64String(param.SecretKey))
100+
{
101+
AddError(responseData, "Secret Key not base64");
102+
}
96103

97104
// Generate a random 16-byte IV for AES in CBC mode
98-
var aesIv = KeyGenerators.GenerateRandomIVKeyAsBytes(16);
105+
byte[] aesIv = Convert.FromBase64String(param.IV);
106+
99107

100108
var byteEncryptionParameters = new ByteEncryptionParameters
101109
{
102-
SecretKey = Convert.FromBase64String(base64secretKey),
110+
SecretKey = Convert.FromBase64String(param.SecretKey),
103111
IV = aesIv,
104-
Data = dataToBeEncrypted.ConvertToHexString().HexadecimalStringToByteArray()
112+
Data = param.Data.ConvertToHexString().HexadecimalStringToByteArray()
105113
};
106114

107115
var response = await BaseAesEncryption.EncryptAsync(byteEncryptionParameters, mode);
108116

109117
return new EncryptionData
110118
{
111119
EncryptedData = Convert.ToBase64String(response),
112-
Iv = Convert.ToBase64String(aesIv),
113-
SecretKey = base64secretKey
120+
Iv = param.IV,
121+
SecretKey = param.SecretKey
114122
};
115123
}
116124

0 commit comments

Comments
 (0)