0

I'm writing a little library using the dart pointycastle library (based on the java bouncycastle).

The libraries don't include any methods for writing a private key to disk.

So I need to write the key to disk after first encrypting it with a pass phrase.

The approach I've taken is to:

  • encode each component of the key (modulus, exponent...) as a base64 string (converted from a bigint)
  • write each base 64 encoded component to a common string
  • encrypt the common string using AES
  • base64 encode the results
  • write the base 64 encoded results to a file.

Is this considered a secure way to store a private key.

I've found this code that I'm using to stretch the passphrase to 128 bits:

 Key stretch(int desiredKeyLength,
      {int iterationCount = 100, Uint8List salt}) {
    if (salt == null) {
      salt = SecureRandom(desiredKeyLength).bytes;
    }

    final params = Pbkdf2Parameters(salt, iterationCount, desiredKeyLength);
    final pbkdf2 = PBKDF2KeyDerivator(Mac('SHA-1/HMAC'))..init(params);

    return Key(pbkdf2.process(_bytes));
  }

Is this adequate?

Brett Sutton
  • 3,900
  • 2
  • 28
  • 53
  • There is no reason to base64 encode anything prior to encryption unless it is somehow easier that way (I'm not familiar with the library or with Dart). The most important thing that you haven't mention is that you must also compute a MAC alongside encryption, and on decrypt you must verify the MAC and reject anything that fails to verify. The easiest way is to use a mode like AES-GCM which **includes the MAC** in the mode itself. – President James K. Polk Aug 18 '20 at 01:37
  • I'm using an AES encryptor. It supoports the following modes: cbc, cfb64, ctr, ecb, ofb64Gctr, ofb64, sic, Currently I'm using sic. Is that adequate? – Brett Sutton Aug 18 '20 at 09:23
  • No, sic does not have authentication built-in. If you can't find an authenticated mode of encryption then you'll have to add a MAC. HMAC is commonly supported. – President James K. Polk Aug 18 '20 at 13:54
  • @PresidentJamesK.Polk I've added a stretch algorithm that I'm now using. Does this do the job? – Brett Sutton Aug 19 '20 at 13:08
  • It looks good but I don't really know dart. You probably want a bigger iteration count than 100. Tens of thousands or more is usually better. – President James K. Polk Aug 20 '20 at 00:11

0 Answers0