Skip to content

Commit

Permalink
Use ReadOnlySpan for RSA DefaultExponent
Browse files Browse the repository at this point in the history
  • Loading branch information
vcsjones committed Mar 27, 2020
1 parent 6380f8c commit 5e4d6c0
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 14 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,32 +16,30 @@ internal static partial class Crypto
internal static extern void BigNumDestroy(IntPtr a);

[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_BigNumFromBinary")]
private static extern IntPtr BigNumFromBinary(byte[] s, int len);
private static extern unsafe IntPtr BigNumFromBinary(byte* s, int len);

[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_BigNumToBinary")]
private static extern unsafe int BigNumToBinary(SafeBignumHandle a, byte* to);

[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetBigNumBytes")]
private static extern int GetBigNumBytes(SafeBignumHandle a);

private static IntPtr CreateBignumPtr(byte[] bigEndianValue)
private static unsafe IntPtr CreateBignumPtr(ReadOnlySpan<byte> bigEndianValue)
{
if (bigEndianValue == null)
fixed (byte* pBigEndianValue = bigEndianValue)
{
return IntPtr.Zero;
}
IntPtr ret = BigNumFromBinary(pBigEndianValue, bigEndianValue.Length);

IntPtr ret = BigNumFromBinary(bigEndianValue, bigEndianValue.Length);
if (ret == IntPtr.Zero)
{
throw CreateOpenSslCryptographicException();
}

if (ret == IntPtr.Zero)
{
throw CreateOpenSslCryptographicException();
return ret;
}

return ret;
}

internal static SafeBignumHandle CreateBignum(byte[] bigEndianValue)
internal static SafeBignumHandle CreateBignum(ReadOnlySpan<byte> bigEndianValue)
{
IntPtr handle = CreateBignumPtr(bigEndianValue);
return new SafeBignumHandle(handle, true);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public sealed partial class RSAOpenSsl : RSA
private const int BitsPerByte = 8;

// 65537 (0x10001) in big-endian form
private static readonly byte[] s_defaultExponent = { 0x01, 0x00, 0x01 };
private static ReadOnlySpan<byte> DefaultExponent => new byte[] { 0x01, 0x00, 0x01 };

private Lazy<SafeRsaHandle> _key;

Expand Down Expand Up @@ -593,7 +593,7 @@ private SafeRsaHandle GenerateKey()

try
{
using (SafeBignumHandle exponent = Interop.Crypto.CreateBignum(s_defaultExponent))
using (SafeBignumHandle exponent = Interop.Crypto.CreateBignum(DefaultExponent))
{
// The documentation for RSA_generate_key_ex does not say that it returns only
// 0 or 1, so the call marshals it back as a full Int32 and checks for a value
Expand Down

0 comments on commit 5e4d6c0

Please sign in to comment.