I want to hash a message with the RSA class using f#.
Currently, I managed to create these few lines using the default randomly generated key pair.
let rsa = RSA.Create()
let dataInBytes = System.Text.Encoding.UTF8.GetBytes ("Message to be hashed.")
let bytes = rsa.SignData(dataInBytes, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1)
In order to use my own private/public key pair I want to use .ImportPkcs8PrivateKey(). My code is:
let privKey = System.IO.File.ReadAllText @"C:\Users\User\Documents\FSharp\privkey.pem";;
val privKey: string =
"-----BEGIN PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFAASC"+[1671 chars]
let convertFromBase64ToBytes (input: string) =
let str = match input.Length % 4 with
| 1 -> input.Substring (1, input.Length - 1)
| 2 -> input + string "=="
| 3 -> input + string "="
| _ -> input
let strReplaced = str
.Replace("-", "+")
.Replace("_", "/")
System.Convert.FromBase64String strReplaced
let privKeyBytes = convertFromBase64ToBytes privKey
> rsa.ImportPkcs8PrivateKey (privKeyBytes);;
but it throws me the error:
System.Security.Cryptography.CryptographicException: ASN1 corrupted data.
---> System.Formats.Asn1.AsnContentException: The encoded length exceeds the maximum supported by this library (Int32.MaxValue).
at System.Formats.Asn1.AsnDecoder.ReadLength(ReadOnlySpan`1 source, AsnEncodingRules ruleSet, Int32& bytesConsumed)
at System.Formats.Asn1.AsnDecoder.ReadEncodedValue(ReadOnlySpan`1 source, AsnEncodingRules ruleSet, Int32& contentOffset, Int32& contentLength, Int32& bytesConsumed)
at System.Security.Cryptography.CngPkcs8.ImportPkcs8PrivateKey(ReadOnlySpan`1 source, Int32& bytesRead)
--- End of inner exception stack trace ---
at System.Security.Cryptography.CngPkcs8.ImportPkcs8PrivateKey(ReadOnlySpan`1 source, Int32& bytesRead)
at System.Security.Cryptography.RSAImplementation.RSACng.ImportPkcs8PrivateKey(ReadOnlySpan`1 source, Int32& bytesRead)
at <StartupCode$FSI_0012>.$FSI_0012.main@() in C:\Users\User\PowerShell\stdin:line 26
Stopped due to error
What am I missing?