Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 42 additions & 27 deletions SecretKey.Core.Tests/CryptoTests.cs
Original file line number Diff line number Diff line change
@@ -1,57 +1,72 @@
using System.Text;
using SecretKey.Core;
using static SecretKey.Core.Tests.TestHelper;

namespace SecretKey.Core.Tests;

/// <summary>
/// Known-answer tests for the building blocks in Crypto.cs.
/// If any of these fail, previously generated passwords can no longer be reproduced.
/// Tests for the building blocks of the password math (docs/password-derivation.md).
/// </summary>
public class CryptoTests
{
[Fact]
public void MonthlyMasterKey_IsSha256OfRootKeyTextPlusDateCode()
public void MonthlyKey_IsKnownValue()
{
byte[] key = Crypto.DeriveMonthlyMasterKey(V1TestHelper.TestRootKey, "2611");

Assert.Equal("4E0F0B5B77491DCA67A584A58EC1F6D4859775346265F8C03B51878FE2CF8A12", Convert.ToHexString(key));
Assert.Equal("D38F4A15A5783BA78B9A80FF2D2AA0FA8086E6AB88D33C9A20206978658A3BB6", Convert.ToHexString(MonthlyKey("2611")));
Assert.Equal("A516AF24CE369E121466A7FD928EC7170CC44590FC6DAAC0E1B77DFD326C9702", Convert.ToHexString(MonthlyKey("2612")));
}

[Fact]
public void HmacSha256_MatchesRfc4231TestCase2()
public void RootKey_IgnoresLetterCaseAndSurroundingSpaces()
{
byte[] mac = Crypto.HmacSha256(Encoding.ASCII.GetBytes("Jefe"), Encoding.ASCII.GetBytes("what do ya want for nothing?"));
byte[] expected = MonthlyKey("2611");

Assert.Equal("5BDCC146BF60754E6A042426089575C75A003F089D2739839DEC58B964EC3843", Convert.ToHexString(mac));
Assert.Equal(expected, Crypto.DeriveMonthlyMasterKey(TestRootKey.ToLowerInvariant(), "2611"));
Assert.Equal(expected, Crypto.DeriveMonthlyMasterKey(" " + TestRootKey + "\n", "2611"));
}

[Fact]
public void HmacSha256_OfAccountBlock_IsStable()
[Theory]
[InlineData("")]
[InlineData("REPLACE_WITH_YOUR_ROOT_KEY")]
[InlineData("000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1")] // 63 characters
[InlineData("000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F00")] // 66 characters
[InlineData("G00102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F")] // not hexadecimal
public void RootKey_ThatIsNot32HexBytes_IsRejected(string badKey)
{
byte[] key = Crypto.DeriveMonthlyMasterKey(V1TestHelper.TestRootKey, "2611");
var block = new byte[32]; // v1: title + url + username, UTF-8, cut or zero-padded to 32 bytes
byte[] text = Encoding.UTF8.GetBytes("Bank" + "https://bank.example" + "ed");
Array.Copy(text, block, text.Length);

Assert.Equal("0F803F563CA1F44777139CCC4BB04B81DA0373509D3D28FC76E896BB234AD5C9", Convert.ToHexString(Crypto.HmacSha256(key, block)));
Assert.Throws<ArgumentException>(() => Crypto.DeriveMonthlyMasterKey(badKey, "2611"));
}

[Fact]
public void MapBlobToPattern_MapsEachMaskTokenFromOneHashByte()
public void EncodeFields_WritesBigEndianLengthThenUtf8()
{
byte[] bytes = Enumerable.Range(0, 32).Select(i => (byte)i).ToArray();
Assert.Equal(
new byte[] { 0, 0, 0, 1, (byte)'a', 0, 0, 0, 0, 0, 0, 0, 2, 0xC3, 0xA9 },
Crypto.EncodeFields("a", "", "é"));
}

// X -> A-Z, x -> a-z, N -> 0-9, S -> "!@#$%&*()-_=+[]{}<>?", anything else is copied as-is.
// A literal still uses up a hash byte (v1 behavior).
Assert.Equal("Ab2$-Fg7)", Crypto.MapBlobToPattern(bytes, "XxNS-XxNS"));
[Theory]
[InlineData("X", new byte[] { 234, 255, 0 }, "A")] // 234 and 255 are skipped for 26-letter sets
[InlineData("x", new byte[] { 233 }, "z")] // 233 is the highest accepted byte: 233 mod 26 = 25
[InlineData("N", new byte[] { 250, 249 }, "9")] // digits accept bytes below 250
[InlineData("S", new byte[] { 240, 239 }, "?")] // symbols accept bytes below 240
[InlineData("X-x.N", new byte[] { 0, 1, 2 }, "A-b.2")] // other characters are copied and use no bytes
public void MapStreamToMask_SkipsBiasedBytes(string mask, byte[] stream, string expected)
{
Assert.Equal(expected, Crypto.MapStreamToMask(stream, mask));
}

[Fact]
public void MapBlobToPattern_WrapsAfter32Characters_V1Behavior()
public void MapStreamToMask_FailsLoudlyIfStreamRunsOut()
{
byte[] bytes = Enumerable.Range(0, 32).Select(i => (byte)i).ToArray();
Assert.Throws<InvalidOperationException>(() => Crypto.MapStreamToMask(new byte[] { 255 }, "x"));
}

// Known v1 weakness: mask positions 33+ reuse the same 32 hash bytes.
Assert.Equal("0123456789012345678901234567890101234567", Crypto.MapBlobToPattern(bytes, new string('N', 40)));
[Fact]
public void NormalizeUrl_AddsHttpsOnlyWhenNoScheme()
{
Assert.Equal("", Crypto.NormalizeUrl(" "));
Assert.Equal("https://paramountplus.com", Crypto.NormalizeUrl(" paramountplus.com "));
Assert.Equal("https://httpbin.org", Crypto.NormalizeUrl("httpbin.org"));
Assert.Equal("http://example.org", Crypto.NormalizeUrl("http://example.org"));
Assert.Equal("HTTPS://Example.com", Crypto.NormalizeUrl("HTTPS://Example.com"));
}
}
112 changes: 112 additions & 0 deletions SecretKey.Core.Tests/PasswordDerivationTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
using static SecretKey.Core.Tests.TestHelper;

namespace SecretKey.Core.Tests;

/// <summary>
/// Locks the passwords SecretKey produces (password math version 2, docs/password-derivation.md).
///
/// Why this exists: the whole point of SecretKey is that the same root key and date code
/// give the same passwords forever. If any test here fails, a code change has altered
/// users' passwords. Do not "fix" the expected values to make a test pass. Change the
/// code back, or put the new behavior behind an explicit new version.
/// </summary>
public class PasswordDerivationTests
{
[Theory]
[InlineData("Bhphotovideo", "https://www.bhphotovideo.com", "email@sample.com", DefaultMask, "2611", "Fiipc3]jpv38")]
[InlineData("Bhphotovideo", "https://www.bhphotovideo.com", "email@sample.com", DefaultMask, "2612", "Fnisb8-erb99")]
[InlineData("Paramount+", "paramountplus.com", "email@yahoo.com", DefaultMask, "2611", "Xxkch8{gnc91")]
[InlineData("Paramount+", "paramountplus.com", "email@yahoo.com", "xxxxxxxxNNNN", "2611", "hleziocv3322")]
[InlineData("MTA eTix", "https://www.mta.info/", "email@sample.com", DefaultMask, "2611", "Qlljp5[oht46")]
[InlineData("Solterra", "", "email@sample.com", DefaultMask, "2611", "Iuxxy3$rud15")]
[InlineData("Old Site", "http://example.org", "me", DefaultMask, "2611", "Xipxr9[mxi91")]
[InlineData("PayPal", "WWW.PayPal.com", "ed", DefaultMask, "2611", "Hggpe8_fvq80")]
[InlineData("Httpbin", "httpbin.org", "me", DefaultMask, "2611", "Egtku9-cfo98")]
[InlineData("Café", "https://café.example", "josé", DefaultMask, "2611", "Iuenu3{gbu25")]
[InlineData("Bank", "https://bank.example", "ed", "Xxx-NNN.x", "2611", "Haj-814.w")]
[InlineData("Long", "https://long.example", "me", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "2611", "ilfatcuwqmrjhrcjasefmjhhaewksivvwvzbnqgt")]
public void KnownAccounts_ProduceKnownPasswords(string title, string url, string username, string mask, string dateCode, string expected)
{
Assert.Equal(expected, Password(title, url, username, mask, dateCode));
}

[Fact]
public void DifferentLoginsOnTheSameSite_GetDifferentPasswords()
{
// v1 gave both of these the same password because only the first 32 bytes counted.
Assert.Equal("Ahluk3(oqe46", Password("Bhphotovideo", "https://www.bhphotovideo.com", "alice@sample.com"));
Assert.Equal("Yzlls2>wli85", Password("Bhphotovideo", "https://www.bhphotovideo.com", "bob@other.org"));
}

[Fact]
public void FieldsCannotRunTogether()
{
// v1 gave ("ab", "", "c") and ("a", "", "bc") the same password.
Assert.Equal("Snapz9[amp36", Password("ab", "", "c"));
Assert.Equal("Yreib0$zwl99", Password("a", "", "bc"));
}

[Fact]
public void LongMask_DoesNotRepeat()
{
string password = Password("Long", "https://long.example", "me", new string('x', 40));

Assert.NotEqual(password[..8], password[32..]);
}

[Fact]
public void ChangingTheMask_GivesAnUnrelatedPassword()
{
Assert.Equal("hzfqhyct", Password("Masks", "https://masks.example", "me", "xxxxxxxx"));
Assert.Equal("gxsjunbz69", Password("Masks", "https://masks.example", "me", "xxxxxxxxNN"));
}

[Fact]
public void AccentsTypedEitherWay_GiveTheSamePassword()
{
// "é" as one character (U+00E9) or as "e" + combining accent (U+0301).
Assert.Equal(
Password("Café", "https://café.example", "josé"),
Password("Café", "https://café.example", "josé"));
}

[Fact]
public void Csv_ProducesNormalizedFieldsAndPasswords()
{
string[] lines = Run(new[]
{
Row("Paramount+", "paramountplus.com", "email@yahoo.com"),
Row(" Padded ", " example.com ", " user "),
"\" Padded \",\" example.com \",\" user \",,,false,false,,",
"\"Smith, John Bank\",https://bank.example,john,,,false,false,,",
Row("Café", "https://café.example", "josé"),
});

Assert.Equal(new[]
{
OutputHeader,
"Paramount+,https://paramountplus.com,email@yahoo.com,Xxkch8{gnc91",
"Padded,https://example.com,user,Mbcza0=lmb30",
"Padded,https://example.com,user,Mbcza0=lmb30",
"\"Smith, John Bank\",https://bank.example,john,Ykiid5=rrm94",
"Café,https://café.example,josé,Iuenu3{gbu25",
}, lines);
}

[Fact]
public void SampleInputFile_ProducesKnownOutput()
{
// Solterra's "passwordmask=" note is not applied yet, so it gets the default mask.
string sample = Path.Combine(AppContext.BaseDirectory, "TestData", "sample_input.csv");
string[] rows = File.ReadAllLines(sample).Skip(1).ToArray();

Assert.Equal(new[]
{
OutputHeader,
"Bhphotovideo,https://www.bhphotovideo.com,email@sample.com,Fiipc3]jpv38",
"Paramount+,https://paramountplus.com,email@yahoo.com,Xxkch8{gnc91",
"Solterra,,email@sample.com,Iuxxy3$rud15",
"MTA eTix,https://www.mta.info/,email@sample.com,Qlljp5[oht46",
}, Run(rows));
}
}
110 changes: 0 additions & 110 deletions SecretKey.Core.Tests/PasswordDerivationV1Tests.cs

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@
namespace SecretKey.Core.Tests;

/// <summary>
/// Shared setup for the v1 known-answer tests.
/// Every expected value in this project was produced by the v1.0.0 engine and
/// cross-checked against an independent implementation of the same algorithm.
/// Shared setup for the password tests.
/// Every expected password in this project was produced by the engine and independently
/// re-computed from docs/password-derivation.md by a separate implementation.
/// </summary>
internal static class V1TestHelper
internal static class TestHelper
{
// TEST-ONLY root key. Never use this for real passwords.
public const string TestRootKey = "000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F";
Expand All @@ -18,6 +18,12 @@ internal static class V1TestHelper
public const string InputHeader = "Title,Url,Username,Password,OTPAuth,Favorite,Archived,Tags,Notes";
public const string OutputHeader = "Title,Url,Username,Password";

public static byte[] MonthlyKey(string dateCode = DateCode) =>
Crypto.DeriveMonthlyMasterKey(TestRootKey, dateCode);

public static string Password(string title, string url, string username, string mask = DefaultMask, string dateCode = DateCode) =>
Crypto.GeneratePassword(MonthlyKey(dateCode), title, url, username, mask);

/// <summary>Builds an unquoted input row in the 1Password-style column order the engine reads.</summary>
public static string Row(string title, string url, string username) =>
$"{title},{url},{username},,,false,false,,";
Expand All @@ -36,7 +42,7 @@ public static string[] Run(IEnumerable<string> inputRows, string mask = DefaultM
string output = Path.Combine(dir, "output.csv");
File.WriteAllLines(input, new[] { InputHeader }.Concat(inputRows));

Processor.Process(input, output, Crypto.DeriveMonthlyMasterKey(TestRootKey, dateCode), mask);
Processor.Process(input, output, MonthlyKey(dateCode), mask);

return File.ReadAllLines(output);
}
Expand All @@ -45,13 +51,4 @@ public static string[] Run(IEnumerable<string> inputRows, string mask = DefaultM
Directory.Delete(dir, recursive: true);
}
}

/// <summary>Runs one account through the engine and returns its output line.</summary>
public static string OutputLineFor(string title, string url, string username, string mask = DefaultMask, string dateCode = DateCode)
{
string[] lines = Run(new[] { Row(title, url, username) }, mask, dateCode);
Assert.Equal(2, lines.Length);
Assert.Equal(OutputHeader, lines[0]);
return lines[1];
}
}
Loading
Loading