Click here to Skip to main content
15,891,473 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I want to decrypt an encrypted string using RSA 2048 Algorithm. I am able to encrypt the same successfully. But while decrypting I am getting the exception as below:
The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters. 


What I have tried:

RSA Encryption:

#region Encrypt_AES_With_CBPublicKey
   public  string Encrypt_AES_With_CBPublicKey(CBAPIDetails objReqAPI)//string Request_AES_string,string RSAPrivateKey
   {
       try
       {
           txtLog.Text += "Client:Encryption of AES Key with CB Public Key started under : " + MethodInfo.GetCurrentMethod().Name + Environment.NewLine;
           /* Bouncy Castle */
           //var keyBytes =
           //Convert.FromBase64String(objReqAPI.AES_KEY); // your key here Deept

           ////var keyBytes =
           ////Convert.FromBase64String("test1"); // your key here Deept

           //var eng = new Pkcs1Encoding(new RsaEngine());
           //using (var reader = File.OpenText(NeSTCommonClass.CB_Public_KeyFile)) // file containing RSA PKCS1 private key
           //{
           //    var keyParameter = (AsymmetricKeyParameter)new PemReader(reader).ReadObject();

           //    eng.Init(true, keyParameter);
           //}

           //var encrypted = Convert.ToBase64String(eng.ProcessBlock(keyBytes, 0, keyBytes.Length));

           //return encrypted;

           /* Bouncy Castle */

           /* Without Bouncy Castle Working here */

           var publicKey = "<RSAKeyValue><Modulus>21wEnTU+mcD2w0Lfo1Gv4rtcSWsQJQTNa6gio05AOkV/Er9w3Y13Ddo5wGtjJ19402S71HUeN0vbKILLJdRSES5MHSdJPSVrOqdrll/vLXxDxWs/U0UT1c8u6k/Ogx9hTtZxYwoeYqdhDblof3E75d9n2F0Zvf6iTb4cI7j6fMs=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";

           //var publicKey = Modulus(Common.ReadTextFile(Common.CB_Public_KeyFile));


           var AESkeyBytes = Encoding.UTF8.GetBytes(objReqAPI.AES_KEY);

           using (var rsa = new RSACryptoServiceProvider(2048))
           {
               try
               {
                   // client encrypting data with public key issued by server
                   rsa.FromXmlString(publicKey.ToString());

                   var encryptedData = rsa.Encrypt(AESkeyBytes, true);

                   var base64Encrypted = Convert.ToBase64String(encryptedData);
                   txtLog.Text += "Client:Encryption of AES Key with CB Public Key Finished under : " + MethodInfo.GetCurrentMethod().Name + Environment.NewLine;
                   return base64Encrypted;
               }
               finally
               {
                   rsa.PersistKeyInCsp = false;
               }
           }

       }
       catch (Exception ex)
       {
           //NeSTCommonClass.WriteTextFile(LogPath + Logfilename, "Encryption with RSA Private Key Failed:" + ex.Message.ToString() + "", true);
           throw ex;
       }


   }


   #region Modulus
   public static string Modulus(string pem)
   {
       byte[] x509der = null;

      x509der = Convert.FromBase64String(pem.Replace("-----BEGIN PUBLIC KEY-----", "").Replace("-----END PUBLIC KEY-----", ""));



      byte[] seqOID = { 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01 };

       MemoryStream ms = new MemoryStream(x509der);
       BinaryReader reader = new BinaryReader(ms);

       if (reader.ReadByte() == 0x30) ReadASNLength(reader); //skip the size
       else return null;

       int identifierSize = 0; //total length of Object Identifier section

       if (reader.ReadByte() == 0x30) identifierSize = ReadASNLength(reader);
       else return null;

       if (reader.ReadByte() == 0x06) //is the next element an object identifier?
       {
           int oidLength = ReadASNLength(reader);
           byte[] oidBytes = new byte[oidLength];
           reader.Read(oidBytes, 0, oidBytes.Length);

           if (oidBytes.SequenceEqual(seqOID) == false) return null; //is the object identifier rsaEncryption PKCS#1?

           int remainingBytes = identifierSize - 2 - oidBytes.Length;
           reader.ReadBytes(remainingBytes);
       }

       if (reader.ReadByte() == 0x03) //is the next element a bit string?
       {
           ReadASNLength(reader); //skip the size
           reader.ReadByte(); //skip unused bits indicator
           if (reader.ReadByte() == 0x30)
           {
               ReadASNLength(reader); //skip the size
               if (reader.ReadByte() == 0x02) //is it an integer?
               {
                   int modulusSize = ReadASNLength(reader);
                   byte[] modulus = new byte[modulusSize];
                   reader.Read(modulus, 0, modulus.Length);
                   if (modulus[0] == 0x00) //strip off the first byte if it's 0
                   {
                       byte[] tempModulus = new byte[modulus.Length - 1];
                       Array.Copy(modulus, 1, tempModulus, 0, modulus.Length - 1);
                       modulus = tempModulus;
                   }

                   if (reader.ReadByte() == 0x02) //is it an integer?
                   {
                       int exponentSize = ReadASNLength(reader);
                       byte[] exponent = new byte[exponentSize];
                       reader.Read(exponent, 0, exponent.Length);

                       RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
                       RSAParameters RSAKeyInfo = new RSAParameters();
                       RSAKeyInfo.Modulus = modulus;
                       RSAKeyInfo.Exponent = exponent;
                       rsa.ImportParameters(RSAKeyInfo);
                       // return rsa.ToXmlString(false).Replace("<RSAKeyValue><Modulus>", "").Replace("</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>", "");

                       return rsa.ToXmlString(false);
                   }
               }
           }
       }

       return null;
   }
   #endregion


   #region ReadASNLength
   public static int ReadASNLength(BinaryReader reader)
   {//Note: this method only reads lengths up to 4 bytes long as this is satisfactory for the majority of situations.
       int length = reader.ReadByte();
       if ((length & 0x00000080) == 0x00000080) //is the length greater than 1 byte
       {
           int count = length & 0x0000000f;
           byte[] lengthBytes = new byte[4];
           reader.Read(lengthBytes, 4 - count, count);
           Array.Reverse(lengthBytes); //
           length = BitConverter.ToInt32(lengthBytes, 0);
       }
       return length;
   }
   #endregion

   #endregion

RSA Decryption:
#region AES_Decrypt_CB_Private_Key
     public string AES_Decrypt_CB_Private_Key(CBAPIDetails objReqAPI)
     {

         try
         {

             /* Bouncy Castle */
             //string CBPvtKeyString=Common.ReadTextFile(Common.CB_Private_KeyFile);
             //CBPvtKeyString = CBPvtKeyString.Replace("-----BEGIN RSA PRIVATE KEY-----", "").Replace("-----END RSA PRIVATE KEY-----", "");
             //var keyBytes =
             // Convert.FromBase64String(Common.CB_PrivateKey); // your key here

             //RsaPrivateCrtKeyParameters privateKey = (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(keyBytes);
             //IAsymmetricBlockCipher eng = new Org.BouncyCastle.Crypto.Encodings.Pkcs1Encoding(new Org.BouncyCastle.Crypto.Engines.RsaEngine());
             //eng.Init(false, privateKey);
             //var base64Encrypted = objReqAPI.encrypyedRequestKeyData;
             //byte[] encdata = System.Convert.FromBase64String(objReqAPI.encrypyedRequestKeyData);

             //string result = System.Convert.ToBase64String(eng.ProcessBlock(encdata, 0, encdata.Length));
             //return result;

             /* Bouncy Castle */

             /* Without Bouncy Castle Working here */
             //var privateKey = "<RSAKeyValue><Modulus>21wEnTU+mcD2w0Lfo1Gv4rtcSWsQJQTNa6gio05AOkV/Er9w3Y13Ddo5wGtjJ19402S71HUeN0vbKILLJdRSES5MHSdJPSVrOqdrll/vLXxDxWs/U0UT1c8u6k/Ogx9hTtZxYwoeYqdhDblof3E75d9n2F0Zvf6iTb4cI7j6fMs=</Modulus><Exponent>AQAB</Exponent><P>/aULPE6jd5IkwtWXmReyMUhmI/nfwfkQSyl7tsg2PKdpcxk4mpPZUdEQhHQLvE84w2DhTyYkPHCtq/mMKE3MHw==</P><Q>3WV46X9Arg2l9cxb67KVlNVXyCqc/w+LWt/tbhLJvV2xCF/0rWKPsBJ9MC6cquaqNPxWWEav8RAVbmmGrJt51Q==</Q><DP>8TuZFgBMpBoQcGUoS2goB4st6aVq1FcG0hVgHhUI0GMAfYFNPmbDV3cY2IBt8Oj/uYJYhyhlaj5YTqmGTYbATQ==</DP><DQ>FIoVbZQgrAUYIHWVEYi/187zFd7eMct/Yi7kGBImJStMATrluDAspGkStCWe4zwDDmdam1XzfKnBUzz3AYxrAQ==</DQ><InverseQ>QPU3Tmt8nznSgYZ+5jUo9E0SfjiTu435ihANiHqqjasaUNvOHKumqzuBZ8NRtkUhS6dsOEb8A2ODvy7KswUxyA==</InverseQ><D>cgoRoAUpSVfHMdYXW9nA3dfX75dIamZnwPtFHq80ttagbIe4ToYYCcyUz5NElhiNQSESgS5uCgNWqWXt5PnPu4XmCXx6utco1UVH8HGLahzbAnSy6Cj3iUIQ7Gj+9gQ7PkC434HTtHazmxVgIR5l56ZjoQ8yGNCPZnsdYEmhJWk=</D></RSAKeyValue>";

             string CB_Private_Key = Common.ReadTextFile(Common.CB_Private_KeyFile);
             var privateKey = Modulus(CB_Private_Key);



             var testData = Encoding.UTF8.GetBytes(objReqAPI.encrypyedRequestKeyData);

             using (var rsa = new RSACryptoServiceProvider(2048))
             {
                 try
                 {
                     var base64Encrypted = objReqAPI.encrypyedRequestKeyData;

                     // server decrypting data with private key
                     rsa.FromXmlString(privateKey);

                     var resultBytes = Convert.FromBase64String(base64Encrypted);
                     var decryptedBytes = rsa.Decrypt(resultBytes, true);
                     var decryptedData = Encoding.UTF8.GetString(decryptedBytes);
                     return decryptedData.ToString();
                 }
                 finally
                 {
                     rsa.PersistKeyInCsp = false;
                 }
             }
             /* Without Bouncy Castle Working here */



         }


         catch (Exception ex)
         {

             throw ex;
         }


     }


     #endregion
Posted
Updated 23-Jul-18 23:08pm

1 solution

Read the error message, it's pretty clear:
Quote:
The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.

That means exactly what is says - the string you are trying to convert from Base64 is not a valid Base64 string.

So use the debugger, and look at exactly what you have in your string, and where it came from.
We can't do that for you - we have no access to your data...
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900