Click here to Skip to main content
15,891,423 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
I need to make RSA encryption by javascript for the user login password that sent from the login page in web application to the server to be decrypted by C# library provided by http://www.bouncycastle.org/csharp.

using the following code:
C#
// Generate public key using RSA encryption
protected void Session_Start(object sender, EventArgs e)
        {
            if (System.Runtime.Caching.MemoryCache.Default.Get("privateKey") == null)
            {
                RsaKeyPairGenerator rsaKeyPairGnr = new RsaKeyPairGenerator();
                rsaKeyPairGnr.Init(new Org.BouncyCastle.Crypto.KeyGenerationParameters(new SecureRandom(), 1024));
                Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair keyPair = rsaKeyPairGnr.GenerateKeyPair();

                SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyPair.Public);

                var pubKeyPEM = FormatPem(publicKeyInfo.GetEncoded().ToBase64(), "PUBLIC KEY");
                RsaKeyParameters publicKey = (RsaKeyParameters)keyPair.Public;
                RsaKeyParameters privateKey = (RsaKeyParameters)keyPair.Private;

                System.Runtime.Caching.MemoryCache.Default.Add("publicKey", pubKeyPEM, DateTimeOffset.MaxValue);
                System.Runtime.Caching.MemoryCache.Default.Add("publicKeyX", publicKey, DateTimeOffset.MaxValue);
                System.Runtime.Caching.MemoryCache.Default.Add("privateKey", privateKey, DateTimeOffset.MaxValue);
            }
        }
		
// Convert SubjectPublicKeyInfo object to PEM format
private static string FormatPem(string pem, string keyType)
        {
            var sb = new StringBuilder();
            sb.AppendFormat("-----BEGIN {0}-----\n", keyType);

            int line = 1, width = 64;

            while ((line - 1) * width < pem.Length)
            {
                int startIndex = (line - 1) * width;
                int len = line * width > pem.Length
                              ? pem.Length - startIndex
                              : width;
                sb.AppendFormat("{0}\n", pem.Substring(startIndex, len));
                line++;
            }

            sb.AppendFormat("-----END {0}-----\n", keyType);
            return sb.ToString();
        }

//Login aspx : javascript code for the login button get public key and password and encrypt using JSEncrypt library
<asp:Button ID="LoginButton" runat="server" OnClientClick="onLoginButtonClicked()" CommandName="Login" Text="Log In" ValidationGroup="Login1" />

    function onLoginButtonClicked() {
			var key = $("#&lt;%= hdnkey.ClientID%>").val();
            var password = $("#Login1_Password").val();
            var encrypt = new JSEncrypt();
            encrypt.setPublicKey(key);
            var encrypted = encrypt.encrypt(password);
            $("#&lt;%= hdnEncryptedPass.ClientID%>").val(encrypted);
        }


//Login aspx.cs
 protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack) return;
            if (System.Runtime.Caching.MemoryCache.Default.Get("publicKey") != null)
            {
                var publicKey = System.Runtime.Caching.MemoryCache.Default.Get("publicKey");
                this.hdnkey.Value = publicKey.ToString();
            }
		}
		
// servre side code that decrypt the encrypted password using the private key
// it gives error while decrypt in the follwoing line
// byte[] deciphered = cipher.ProcessBlock(ciphered, 0, ciphered.Length);
//the error message is: input too large for RSA cipher.
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
        {
            try
            {
                RsaKeyParameters privateKey = (RsaKeyParameters)System.Runtime.Caching.MemoryCache.Default.Get("privateKey");
                
                string encrypted = this.hdnEncryptedPass.Value;

                SHA512Managed hash = new SHA512Managed();
                SecureRandom randomNumber = new SecureRandom();
                byte[] encodingParam = hash.ComputeHash(Encoding.UTF8.GetBytes(randomNumber.ToString()));

                IAsymmetricBlockCipher cipher = new RsaEngine();
                UTF8Encoding utf8enc = new UTF8Encoding();
                
                cipher.Init(false, privateKey);
                byte[] ciphered = Encoding.UTF8.GetBytes(encrypted);
                byte[] deciphered = cipher.ProcessBlock(ciphered, 0, ciphered.Length);
                var pass = utf8enc.GetString(deciphered);
            }
            catch (Exception ee)
            {

                throw;
            }

            e.Authenticated = Membership.ValidateUser(Login1.UserName, Login1.Password);
        }


What I have tried:

i tried the .NET library on www.bouncycastle.org/csharp but it is server side code only.i need the javascript code that made encryption with RSA encryption and compatible with RSA encryption implemented with C# and .NET framework by the bouncy castle library.
i tried the javascript library Jscript and it failed.
**the Javascript code encrypt the password and send it to server with larger length than the size that the decrypt method accept.
Posted
Updated 9-May-17 2:46am
v2
Comments
F-ES Sitecore 9-May-17 9:00am    
Encryption only works if keys are secret, but in javascript everything is public so you can't keep keys secret. Google "rsa javascript" and if you don't find any solutions why do you think that is? As mentioned in Solution 1, what you're doing has no real merit, you need to say why you are wanting to implement this and see if someone has a solution to it as this is not it.

1 solution

Don't.

Seriously, don't.

What protection do you think this could possibly offer?

If you're trying to stop someone eavesdropping on the communication with your site, get an SSL certificate. Not only will that automatically encrypt the communication between your server and the client, it will also remove the "not secure" warnings that all modern browsers add to any page with a login form that's served over HTTP.

Avoiding the Not Secure Warning in Chrome  |  Web  |  Google Developers[^]
Communicating the Dangers of Non-Secure HTTP | Mozilla Security Blog[^]

Depending on your requirements, it might not even cost you any money: Let's Encrypt - Free SSL/TLS Certificates[^]

Without an SSL certificate, all your code will achieve is to stop the attacker from reading the original password. It won't stop them from capturing the encrypted password and using that to authenticate as the user on your site.
 
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