Skip to content

Commit da3197b

Browse files
Add inverse method for field elements
1 parent 2583e95 commit da3197b

File tree

1 file changed

+55
-9
lines changed

1 file changed

+55
-9
lines changed

Src/Autarkysoft.Bitcoin/Cryptography/EllipticCurve/UInt256_10x26.cs

+55-9
Original file line numberDiff line numberDiff line change
@@ -1719,24 +1719,70 @@ public bool Sqrt(out UInt256_10x26 result)
17191719

17201720

17211721
/// <summary>
1722-
/// Place holder for the non-constant-time implementation
1722+
/// Compute the modular inverse of this field element.
1723+
/// </summary>
1724+
/// <returns>Modular inverse (normalized)</returns>
1725+
public UInt256_10x26 Inverse()
1726+
{
1727+
#if DEBUG
1728+
bool input_is_zero = IsZeroNormalized();
1729+
Verify();
1730+
#endif
1731+
1732+
UInt256_10x26 tmp = Normalize();
1733+
ModInv32Signed30 s = new ModInv32Signed30(tmp);
1734+
ModInv32.Compute(ref s, ModInv32ModInfo.FeConstant);
1735+
UInt256_10x26 r = s.ToUInt256_10x26();
1736+
1737+
#if DEBUG
1738+
Debug.Assert(r.IsZeroNormalized() == input_is_zero);
1739+
r.Verify();
1740+
#endif
1741+
1742+
return r;
1743+
}
1744+
1745+
1746+
/// <summary>
1747+
/// Compute the modular inverse of this field element, without constant-time guarantee.
1748+
/// </summary>
1749+
/// <returns>Modular inverse (normalized)</returns>
1750+
public UInt256_10x26 InverseVar()
1751+
{
1752+
#if DEBUG
1753+
bool input_is_zero = IsZeroNormalized();
1754+
Verify();
1755+
#endif
1756+
1757+
UInt256_10x26 tmp = NormalizeVar();
1758+
ModInv32Signed30 s = new ModInv32Signed30(tmp);
1759+
ModInv32.ComputeVar(ref s, ModInv32ModInfo.FeConstant);
1760+
UInt256_10x26 r = s.ToUInt256_10x26();
1761+
1762+
#if DEBUG
1763+
Debug.Assert(r.IsZeroNormalized() == input_is_zero);
1764+
r.Verify();
1765+
#endif
1766+
1767+
return r;
1768+
}
1769+
1770+
1771+
/// <summary>
1772+
/// Obsolete: Use InverseVar() instead.
17231773
/// </summary>
17241774
/// <returns></returns>
1775+
[Obsolete("Use InverseVar() instead.")]
17251776
public UInt256_10x26 InverseVariable_old()
17261777
{
17271778
return Inverse_old();
17281779
}
17291780

17301781
/// <summary>
1731-
/// Returns the modular inverse of this instance.
1732-
/// Magnitude must be at most 8. The output magnitude will be 1.
1782+
/// Obsolete: Use Inverse() instead.
17331783
/// </summary>
1734-
/// <remarks>
1735-
/// This method is constant-time.
1736-
///
1737-
/// This is the old method in secp256k1 library which will be replaced by the new one later
1738-
/// </remarks>
1739-
/// <returns>Modular inverse</returns>
1784+
/// <returns></returns>
1785+
[Obsolete("Use Inverse() instead.")]
17401786
public UInt256_10x26 Inverse_old()
17411787
{
17421788
UInt256_10x26 x2, x3, x6, x9, x11, x22, x44, x88, x176, x220, x223, t1;

0 commit comments

Comments
 (0)