Store Base64 Encoded values in Cookies (Vbscript)

Is there a way to store Base64 encoded values in cookies?

I.E, rather than creating a cookie with a value of 1 create a cookie with a value of MQ==

I've tried storing this in a cookie, but i believe the cookie removes special characters.

Is there a work around, and how would you do this in VBScript?

Thanks
garethtnashAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Big MontySenior Web Developer / CEO of ExchangeTree.org Commented:
do you already have a Base64 encode function? if so, you should only need to do

Server.URLEncode( val )

to store the value in a cookie, and when you read it, it should automatically decode itself
0
garethtnashAuthor Commented:
Hey Big Monty,

Yes,

So I guess I would use

Base64Encode(Server.URLEncode( val )) to store

How would I unencode?

Base64Decode(???(val))

There isn't a Server.URLdecode in vbscript?

and is it url encode or html encode?

Thanks
0
Big MontySenior Web Developer / CEO of ExchangeTree.org Commented:
you have good timing, because I just spent a day earlier this week working on Base64Encoding :)

stick the following code in it's own file, and then include that file into your main page:

function md5hashBytes(aBytes)
    Dim MD5
    set MD5 = CreateObject("System.Security.Cryptography.MD5CryptoServiceProvider")

    MD5.Initialize()
    'Note you MUST use computehash_2 to get the correct version of this method, and the bytes MUST be double wrapped in brackets to ensure they get passed in correctly.
    md5hashBytes = MD5.ComputeHash_2( (aBytes) )
end function

function stringToUTFBytes(aString)
    Dim UTF8
    Set UTF8 = CreateObject("System.Text.UTF8Encoding")
    stringToUTFBytes = UTF8.GetBytes_4(aString)
end function

function bytesToHex(aBytes)
    dim hexStr, x
    for x=1 to lenb(aBytes)
        hexStr= hex(ascb(midb( (aBytes),x,1)))
        if len(hexStr)=1 then hexStr="0" & hexStr
        bytesToHex=bytesToHex & hexStr
    next
end function

Function BytesToBase64(varBytes)
    With CreateObject("MSXML2.DomDocument").CreateElement("b64")
        .dataType = "bin.base64"
        .nodeTypedValue = varBytes
        BytesToBase64 = .Text
    End With
End Function

Function GetBytes(sPath)
    With CreateObject("Adodb.Stream")
        .Type = 1 ' adTypeBinary
        .Open
        .LoadFromFile sPath
        .Position = 0
        GetBytes = .Read
        .Close
    End With
End Function

Open in new window


I got this code from a site to not be named and have tested and verified it works. to do Base64 encoding, simply do:

encodedValue = BytesToBase64(md5hashBytes(stringToUTFBytes(valueToEncode)))

this alone should allow you to save it to a cookie. Give that a shot and see if it works. if so, then we can move on.
0
Cloud Class® Course: Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

garethtnashAuthor Commented:
Hi Big Monty,

thats worked - it encoded 2 as yB5yjZ1ML2NvBn%BJzBSGLA%3D%3D

How do i reverse that now, so that I can use the 2 in server scripts?

Thanks

:)
0
Big MontySenior Web Developer / CEO of ExchangeTree.org Commented:
that doesn't seem right, the number 2 wouldn't decode to that. can i see the code you used?
0
Big MontySenior Web Developer / CEO of ExchangeTree.org Commented:
just found these functions as well, includes decoding, may be worth using in your case:

http://www.freevbcode.com/ShowCode.asp?ID=5248
0
garethtnashAuthor Commented:
Hey Big Monty,

Apologies for the late response; below you can see my code.

VBscript that logs user in and creates cookies

<!--#include virtual="/Connections/joter.asp" -->
<!--#include virtual="/scripts/base64.asp" -->
<!--#include virtual="/scripts/MD5.asp" -->
<%
if Request("signinusername") <> "" AND Request("signinpassword") <> "" then

Dim CMDLogin__Username
CMDLogin__Username = NULL
if(Request("signinusername") <> "") then CMDLogin__Username = Trim(Request("signinusername"))

Dim CMDLogin__Password
CMDLogin__Password = NULL
if(Request("signinpassword") <> "") then CMDLogin__Password = Trim(Request("signinpassword"))

set CMDLogin = Server.CreateObject("ADODB.Command")
CMDLogin.ActiveConnection = MM_Conn_STRING
CMDLogin.CommandText = "dbo.CLogin"
CMDLogin.CommandType = 4
CMDLogin.CommandTimeout = 0
CMDLogin.Prepared = true
CMDLogin.Parameters.Append CMDLogin.CreateParameter("@RETURN_VALUE", 3, 4)
CMDLogin.Parameters.Append CMDLogin.CreateParameter("@Username", 200, 1,350,CMDLogin__Username)
CMDLogin.Parameters.Append CMDLogin.CreateParameter("@Password", 200, 1,50,CMDLogin__Password)
set Login = CMDLogin.Execute
Login_numRows = 0

If not Login.eof then
arrLogin = Login.GetRows()
End if 

Login.Close() 'Clean Up
Set Login = Nothing 'Clean Up
Set CMDLogin = Nothing 'Clean Up

	Dim result
	
	If IsArray(arrLogin) Then
		dim candlogin 
		For candlogin = 0 to ubound(arrLogin, 2)

			if arrLogin(0,candlogin) = 1 then

				'Response.write(1)
				result = 1

			Elseif arrLogin(0,candlogin) = 2 then

				'Response.write(1)
				result = 2
				
			Elseif arrLogin(0,candlogin) = 3 then

		        Response.Cookies("UserAuth")("Userid")= arrLogin(1,candlogin)
    		    Response.Cookies("UserAuth")("Authentication")= arrLogin(2,candlogin)
    		    Response.Cookies("UserAuth")("UserEmail")= arrLogin(3,candlogin)
    		    Response.Cookies("UserAuth")("LoggedIn")=Date
    		    Response.Cookies("Auth")= BytesToBase64(md5hashBytes(stringToUTFBytes(arrLogin(1,candlogin))))

		        ' If request("rememberme") is null then
		        If IsNull(request("SignInRememberMe")) Then
        		    Response.Cookies("UserAuth").Expires = dateAdd("n", 20, Now())
		    	end if
				result = 3
			end if
		Next
	end If
end if

Response.Write(result)
%>

Open in new window


The form that sends the variables -

<form action="" method="post" name="SignIn" class="fancyform" id="SignIn">
  <h3>Sign in</h3>
    <div class="alert" id="SignInError1" style="display:none;"></div>
    <div class="alert" id="SignInError2" style="display:none;"></div>
  <div class="halfbox">
    <label for="signinusername">Email Username</label>
    <input name="signinusername" type="email" required="required" id="signinusername" form="SignIn" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$" value="" maxlength="255" /><br/>
    </div>
    <div class="halfbox">
    <label for="signinusername">Password</label>
    <input name="signinpassword" type="password" required="required" id="signinpassword" form="SignIn" maxlength="255" /><br/>
    </div>
    <div class="labeldiv">
      <label title="Tick this option to have this computer / device store your login credentials">
                                                <input type="checkbox" name="rememberme" id="SignInRememberMe" value="true" checked="checked">
                                                Remember me
      </label>
    </div>
    <div class="linkdiv">
                                        <a class="fancybox" href="#PasswordRequestfrm" rel="nofollow">Forgotten your password?</a>    </div><input name="Sign In" type="submit" disabled="disabled" id="SignInSubmit" form="SignIn" value="Sign in" />
  <input name="Cancel" type="button" onclick="$.fancybox.close()" class="cancelbutton closefb" id="SignInCancel" form="SignIn" value="Cancel" />
  <input type="hidden" name="returnUrl4" value="">
</form>

Open in new window


The JQuery that submits the form -

  $("#SignIn").submit(function(e){
      e.preventDefault();
    $.ajax({
		type: "POST",
        url: "/actions/login.asp",
        data:$(this).serialize(),
		success:function(result){
          $('#SignInError1').hide();
          $('#SignInError2').hide();
         if(result==1){
            // do something fail
			var email = $('#signinusername').val();	
	      $('#SignInError1').html('<p>Sorry there is no account registered with the username ' + email + '. Please <a class="fancybox" href="#Register" rel="nofollow">register</a> an account to continue</p>');
          $('#SignInError1').fadeIn('slow');
          }
		  else if (result==2){
            // do something fail
			var email = $('#signinusername').val();
	      $('#SignInError2').html('<p>The password you have provided is not correct. Please try again or <a class="fancybox" href="#PasswordRequestfrm" rel="nofollow">Reset your password</a></p>');
          $('#SignInError2').fadeIn('slow');
          }
		  else {
            // do something success
     		 $.fancybox.close();
				if (location.pathname == '/passwordreset/passreset.asp') {
				  window.location = '/account/settings.asp';
				}
				else {
				   location.reload();
				}       
			 }
  	  }});
  });

Open in new window


And of course the code you provided -

<%
function md5hashBytes(aBytes)
    Dim MD5
    set MD5 = CreateObject("System.Security.Cryptography.MD5CryptoServiceProvider")

    MD5.Initialize()
    'Note you MUST use computehash_2 to get the correct version of this method, and the bytes MUST be double wrapped in brackets to ensure they get passed in correctly.
    md5hashBytes = MD5.ComputeHash_2( (aBytes) )
end function

function stringToUTFBytes(aString)
    Dim UTF8
    Set UTF8 = CreateObject("System.Text.UTF8Encoding")
    stringToUTFBytes = UTF8.GetBytes_4(aString)
end function

function bytesToHex(aBytes)
    dim hexStr, x
    for x=1 to lenb(aBytes)
        hexStr= hex(ascb(midb( (aBytes),x,1)))
        if len(hexStr)=1 then hexStr="0" & hexStr
        bytesToHex=bytesToHex & hexStr
    next
end function

Function BytesToBase64(varBytes)
    With CreateObject("MSXML2.DomDocument").CreateElement("b64")
        .dataType = "bin.base64"
        .nodeTypedValue = varBytes
        BytesToBase64 = .Text
    End With
End Function

Function GetBytes(sPath)
    With CreateObject("Adodb.Stream")
        .Type = 1 ' adTypeBinary
        .Open
        .LoadFromFile sPath
        .Position = 0
        GetBytes = .Read
        .Close
    End With
End Function
%>

Open in new window


Any thoughts?

Thanks
0
Big MontySenior Web Developer / CEO of ExchangeTree.org Commented:
try using the code in the above link I provided
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
garethtnashAuthor Commented:
thanks
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
VB Script

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.