public static KfxFile Create(ulong uVersion, byte[] pbKey, byte[] pbHash) { if (pbKey == null) { throw new ArgumentNullException("pbKey"); } if (pbKey.Length == 0) { throw new ArgumentOutOfRangeException("pbKey"); } if (uVersion == 0) { uVersion = 0x0002000000000000; } // Null hash: generate one, empty hash: store no hash if (pbHash == null) { pbHash = HashData(pbKey); } VerifyHash(pbKey, pbHash); KfxFile kf = new KfxFile(); if (uVersion == 0x0001000000000000) { kf.Meta.Version = "1.00"; // KeePass <= 2.46 used two zeros } else { kf.Meta.Version = StrUtil.VersionToString(uVersion, 2); } if (uVersion == 0x0001000000000000) { kf.Key.Data.Value = Convert.ToBase64String(pbKey); } else if (uVersion == 0x0002000000000000) { kf.Key.Data.Value = FormatKeyHex(pbKey, 3); if (pbHash.Length != 0) { kf.Key.Data.Hash = MemUtil.ByteArrayToHexString(pbHash); } } else { throw new NotSupportedException(KLRes.FileVersionUnsupported); } return(kf); }
private static byte[] LoadKeyFileXml(byte[] pbFileData) { KfxFile kf; try { using (MemoryStream ms = new MemoryStream(pbFileData, false)) { kf = KfxFile.Load(ms); } } catch (Exception) { return(null); } // We have a syntactically valid XML key file; // failing to verify the key should throw an exception return((kf != null) ? kf.GetKey() : null); }
internal static void Create(string strFilePath, byte[] pbAdditionalEntropy, ulong uVersion) { byte[] pbRandom = CryptoRandom.Instance.GetRandomBytes(32); if ((pbRandom == null) || (pbRandom.Length != 32)) { throw new SecurityException(); } byte[] pbKey; if ((pbAdditionalEntropy == null) || (pbAdditionalEntropy.Length == 0)) { pbKey = pbRandom; } else { int cbAdd = pbAdditionalEntropy.Length; int cbRnd = pbRandom.Length; byte[] pbCmp = new byte[cbAdd + cbRnd]; Array.Copy(pbAdditionalEntropy, 0, pbCmp, 0, cbAdd); Array.Copy(pbRandom, 0, pbCmp, cbAdd, cbRnd); pbKey = CryptoUtil.HashSha256(pbCmp); MemUtil.ZeroByteArray(pbCmp); } KfxFile kf = KfxFile.Create(uVersion, pbKey, null); IOConnectionInfo ioc = IOConnectionInfo.FromPath(strFilePath); using (Stream s = IOConnection.OpenWrite(ioc)) { kf.Save(s); } MemUtil.ZeroByteArray(pbKey); MemUtil.ZeroByteArray(pbRandom); }