RSA Public key encryption using modulus and exponent

0

I want to generate a public key using RSA with given Modulus and Exponent values.

public static string RSAPublic(string toEncrypt) {
    var crypt = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaPkcs1);
    var buffer = CryptographicBuffer.ConvertStringToBinary(toEncrypt, BinaryStringEncoding.Utf8);

    string publikKey = modulus + exponent;
    publikKey.Replace("\r\n", "");

    var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(publikKey);

    string pk = System.Convert.ToBase64String(plainTextBytes);

    IBuffer keyBuffer = CryptographicBuffer.DecodeFromBase64String(pk);



    CryptographicKey key = crypt.ImportPublicKey(keyBuffer, CryptographicPublicKeyBlobType.X509SubjectPublicKeyInfo); // Throws exception here, have tried using all the 4 available BlobTypes



    // var key = crypt.CreateKeyPair(512);
    var sigBuffer = CryptographicEngine.Encrypt(key, buffer, null);
    string signature = CryptographicBuffer.EncodeToBase64String(sigBuffer);
    return signature;
}

Following is the Exception Message : "ASN1 bad tag value met. (Exception from HRESULT: 0x8009310B)"

StackTrace : " at Windows.Security.Cryptography.Core.AsymmetricKeyAlgorithmProvider.ImportPublicKey(IBuffer keyBlob, CryptographicPublicKeyBlobType BlobType) at MyProject.General.Utility.RSAPublic(String toEncrypt)"

I am not able to figure out the right way to generate the CryptographicKey necessary to create encrypted string. Any help would be appreciated.

c#
encryption
windows-phone-8.1
rsa
win-universal-app
asked on Stack Overflow Jul 23, 2015 by nipun.birla • edited Jul 23, 2015 by nipun.birla

1 Answer

0

you should have a look of your public key format, the key format must obey ans.1 rule. look at this question RSA Public Key format

if you still not sure about the format, just use the AsymmetricKeyAlgorithmProvider to create two or three or more public keys and convert them to hex string.

you can find the format.

I use the rsapkcs1 to create a sample public key 30818902818100ae037f0bcb6b4a5b661d7fc43178133b190f12f6c4e0e3ca694d4ec47458862b89691cb06767aa5054a92fc61ec8dc5c53983341c78ba3b95faf887b108093b41632a2ae324b0aaccab4172d83d7691476a6a97683d595355bd0bfa1fa5ea4d9cf2d5836ddb471de1df34ec27b6f0c4f903a13b6700cfb08ada8e43cf3b0cf7b0203010001

if you use the RsaPkcs1 to create key, the public key would start with 30818902818100 ae037f0bcb6b4a5b661d7fc43178133b190f12f6c4e0e3ca694d4ec47458862b89691cb06767aa5054a92fc61ec8dc5c53983341c78ba3b95faf887b108093b41632a2ae324b0aaccab4172d83d7691476a6a97683d595355bd0bfa1fa5ea4d9cf2d5836ddb471de1df34ec27b6f0c4f903a13b6700cfb08ada8e43cf3b0cf7b end with 0203010001

just join the header and the tail to fill the format.

answered on Stack Overflow Feb 1, 2017 by J.Lin • edited May 23, 2017 by Community

User contributions licensed under CC BY-SA 3.0