0

I have a custom objects which will have user information fields and password fields.

Also i have custom LWC (salesforce site) with Username and password. Password has to store in encrypt value.

For Password Encryption I'm using Crypto.generateAesKey.

//Data to encrypt
Blob data = Blob.valueOf(pwd);
//Generate an AES key for the encryption. 
Blob cryptoValue = Crypto.generateAesKey(256);
//Encrypt the data
Blob encryptedData = Crypto.encryptWithManagedIV('AES256', cryptoValue, data);
system.debug('encryptedData' + encryptedData );
String encryptedDataText = EncodingUtil.base64Encode(encryptedData);

But the problem is, Each time for the same string I'm getting new encrypted data.

For Ex: String ='123'

First Time encrypted data ==> WFxOkecVPKd/5AKVgHIdQVSVeyTOjbKQ/VrTo/M43+Hg+kSFqB4yycGyfXJptfnP

For the same string I'm getting different encrypted data uZpw7mGyJmBT7d/p0yHsJGYg46SdqrLMJg8BDApNukROz+U/p5QmdwIJQbl9hOm7

Can you please help, what is the Right way to generate and store the encrypted password.

user3214361
  • 913
  • 6
  • 34
  • 73

1 Answers1

1

This is because you're using a "Managed IV". This means that a random IV is chosen for each time you do an encryption, and is automatically retrieved from the binary data when using decryptWithManagedIV. If you want to have the same value returned each time, choose an IV and use that with encrypt/decrypt.

An IV is the "initialization vector", and acts as a modifier to the key material to produce different outputs for the same key. This is the "salt" that is commonly used in encryption algorithms and prevents rainbow table attacks against exposed encrypted texts.

For storing passwords or other secrets, a Managed IV is probably preferable. This will ensure that two identical passwords will appear different in the database. This will make it more difficult to confirm that two users are using the same password.

As an aside, make sure you read the Terms of Service, Site.com License Agreement, End User License Agreement, and Master Service Agreement to make sure you're not violating any licensing rules by doing this. Generally speaking, you're not allowed to manage passwords directly, you should be using the appropriate type of user (e.g. Site.com user, CRM License, Portal User, etc).

sfdcfox
  • 489,769
  • 21
  • 458
  • 806
  • When i tried to login with user name and password, From my class i have to encrypt the password and authenticate with my custom object fields. In this case while encrypting new key will generated and authentication got failed. This is the problem I'm facing now. – user3214361 Apr 13 '20 at 18:26
  • @user3214361 Like I said, either retrieve the encrypted key and decrypt to verify, or use your own IV. – sfdcfox Apr 13 '20 at 18:29