PCLCrypto asymmetric encryption failing with leading zero padding public key

748 Views Asked by At

Running the following code fails. When I import the public key one of the RSA parameters seems to get padded with a leading zero, causing the publickKey to be 520 bits instead of the 512 bits of the privateKey.

public static void Test()
{
    var algorithm = WinRTCrypto.AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithm.RsaPkcs1);
    ICryptographicKey privateKey = algorithm.CreateKeyPair(512);
    byte[] publicKeyBytes = privateKey.ExportPublicKey(CryptographicPublicKeyBlobType.X509SubjectPublicKeyInfo);
    ICryptographicKey publicKey = algorithm.ImportPublicKey(publickKeyBytes, CryptographicPublicKeyBlobType.X509SubjectPublicKeyInfo);

    var encryptedValue = WinRTCrypto.CryptographicEngine.Encrypt(publicKey, Encoding.UTF8.GetBytes("test"));
    var decryptedValue = WinRTCrypto.CryptographicEngine.Decrypt(privateKey, encryptedValue);
}

The problem seems to be this line:

algorithm.ImportPublicKey(publickKeyBytes, CryptographicPublicKeyBlobType.X509SubjectPublicKeyInfo);

The publicKeyBytes seems right. It works against another service that uses it to encrypt some data that I can succesfully decrypt. This issue is when i try to create some dummy encrypted data for unit testing.

Im running this code in a Portable Class Library using .Net Framework 4.5.

The above code throws at the line where it try's to decrypt, a System.Security.Cryptography.CryptographicExceptionwith the following message:

The data to be decrypted exceeds the maximum for this modulus of 64 bytes.

The following assert fails:

Assert.Equals(privateKey.KeySize, publicKey.KeySize)

Doing the following removeing the padded zero from the Modulus fix the public key and everything works fine.

RSAParameters rsaPublicParameters = publicKey.ExportParameters(false);
rsaPublicParameters.Modulus = rsaPublicParameters.Modulus.Skip(1).ToArray();
ICryptographicKey workingPublicKey = algorithm.ImportParameters(rsaPublicParameters);

Is this a bug in PCLCrypto or am I using it wrong.

0

There are 0 best solutions below