AKushWarrior / steel_crypt

A collection of high-level API's exposing PointyCastle to perform hashing and encrypting in popular/secure algorithms.
https://pub.dev/packages/steel_crypt
Mozilla Public License 2.0
40 stars 10 forks source link

Question: import a key generated using PBKDF2? #20

Closed deiu closed 4 years ago

deiu commented 4 years ago

Hi,

I was wondering if there is a way to import/generate an AES key from a PBKDF2 key.

deiu commented 4 years ago

I managed to find a workaround, by first decoding the base64 string I got from PBKDF2 into a Uint8List, and then recreating an acceptable length string for the AES key.

import 'package:steel_crypt/steel_crypt.dart';
import 'dart:convert';

void main() async {
  // derive the PBKDF2 key
  final passHash = PassCrypt('SHA-256/HMAC/PBKDF2');
  final ivsalt = CryptKey().genDart(16);
  final derivationPassword = 'foobar';
  final derivedHash = passHash.hashPass(ivsalt, derivationPassword);
  // prepare the key to be used by AesCrypt
  final derivedBytes = base64Decode(derivedHash);
  final derivedKey = String.fromCharCodes(derivedBytes);

  // generate the AES key using the derived bytes
  final aesEncrypter = AesCrypt(derivedKey);
  final encrypted = aesEncrypter.encrypt('super secret text', ivsalt); 
  print('Encrypted msg: $encrypted');

  // generated the AES key a 2nd time using the same derived bytes, then use it to  decrypt
  final aesEncrypter2 = AesCrypt(derivedKey);
  print('Decrypted msg: ${aesEncrypter2.decrypt(encrypted, ivsalt)}');
}