Answered by:
ASP.net C# Built-in method for Encrypt/Decrypt Encode/Decode, Passphrase, Expiring url string, AES Compliant with SALT

Question
-
User1045460610 posted
What is a good approach to hide the user id in the url querystring with apassphrase, and expiration with a .net built-in method? Hopefully just one or two lines as listed below.
I use a static page to capture the user id (hostid) and post it by a url string to our automated attendance web site. We don't really want the id visible in the url string. We want the script to be AES compliant with SALT.
Static Page source
href="https://attendance.erpise.com/studentcourse.aspx?HostID=@@HostIDRenders Srtring
https://attendance.erpise.com/studentcourse.aspx?HostID=126186Here is some encode/decode script.
public static string EncodeTo64(string toEncode)
{
var toEncodeAsBytes = Encoding.ASCII.GetBytes(toEncode);
var returnValue = System.Convert.ToBase64String(toEncodeAsBytes);
return returnValue;
}
public static string DecodeFrom64(string encodeData)
{
var encodeDataAsBytes = System.Convert.FromBase64String(encodeData);
var returnValue = Encoding.ASCII.GetString(encodeDataAsBytes);
return returnValue;
}It looks like I would just add a passphrase and a datetimestamp. And check the date is not past an interval such as 30 minutes when I decode it. If expired then redirect back to calling page.
aspx source
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="studentcourse.aspx.cs" Inherits="addcourse" %>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>On Grounds</title>
<style type="text/css">
.auto-style2 {
width: 123px;
}
.auto-style3 {
width: 26px;
}
.auto-style4 {
width: 27px;
}
.auto-style5 {
width: 288px;
}
.auto-style6 {
/*width: 140px;*/
}
</style>
</head>
<body>
<form id="form1" runat="server">
<h2 class="auto-style5">
<asp:Image ID="Image1" runat="server" Height="103px" Width="216px" ImageUrl="~/headerLogo.png" />
</h2>
<h2>
Attendance</h2>
<h2>
Student - Course</h2>
<table>
<tr>
<td class="auto-style2">
Student ID:</td>
<td class="auto-style6"><asp:TextBox ID="txtStudentID" runat="server" Enabled="False" ></asp:TextBox></td>
<td class="auto-style3">
</td>
</tr>
<tr>
<td class="auto-style2">
Student Name:</td>
<td class="auto-style6">
<asp:TextBox ID="txtStudentName" runat="server" Enabled="False"></asp:TextBox></td>
<td class="auto-style3">
</td>
</tr>
<tr>
<td class="auto-style2">
Instructor Name</td>
<td class="auto-style6">
<asp:TextBox ID="txtInstructorName" runat="server" Enabled="False"></asp:TextBox>
</td>
<td class="auto-style3">
</td>
</tr>
<tr>
<td class="auto-style2">
Course Code</td>
<td class="auto-style6">
<asp:TextBox ID="txtCourseCode" runat="server" Enabled="False"></asp:TextBox></td>
<td class="auto-style3">
</td>
</tr>
<tr>
<td class="auto-style2">
Course Title:</td>
<td class="auto-style6">
<asp:TextBox ID="txtCourseTitle" runat="server" Enabled="False"></asp:TextBox></td>
<td class="auto-style3">
</td>
</tr>
<tr>
<td class="auto-style2">
Course Start Time:</td>
<td class="auto-style6">
<asp:TextBox ID="txtCourseStartTime" runat="server" Enabled="False"></asp:TextBox></td>
<td class="auto-style3">
</td>
</tr>
<tr>
<td class="auto-style2">
Attendance Code:</td>
<td class="auto-style6">
<asp:TextBox ID="txtAttendanceCode" runat="server"></asp:TextBox></td>
<td class="auto-style3">
</td>
</tr>
</table>
<br />
<asp:Button ID="btnAdd" runat="server" Text="Save Code" OnClick="btnAdd_Click" />
<br />
<br />
<asp:Button ID="btnHelp" runat="server" Text="?" ToolTip="Instructions/Notes: You must be in the assigned classroom and on the wireless network to post your attendance. If you do not have a smartphone or laptop, borrow one from a friend or see your instructor. Enter the Attendance Code given out by the instructor for this class session and click Save Code" />
<br />
<br />
<asp:Label ID="lblMsg" runat="server" EnableViewState="False"></asp:Label>
<br />
<asp:Label ID="lblMsg2" runat="server" EnableViewState="False"></asp:Label>
<br />
<asp:Label ID="lblMsg3" runat="server" EnableViewState="False" Visible="False"></asp:Label>
<br />
<br />
<table>
<tr>
<%--<td class="auto-style2">
Record ID:</td>--%>
<td>
<asp:TextBox ID="txtRecordID" runat="server" Enabled="False" Width="192px"></asp:TextBox>
</td>
<td class="auto-style4">
</td>
</tr>
<tr>
<%--<td class="auto-style2">
UserID:</td>--%>
<td>
<asp:TextBox ID="txtUserID" runat="server" Width="192px" Enabled="False"></asp:TextBox></td>
<td class="auto-style4">
</td>
</tr>
</table>
<br />
<br />
<asp:Panel ID="Panel1" runat="server" Width="216px">
<br />
<%--Instructions/Notes:
<br />
-You must be in the assigned classroom and on the Parker U wireless network to post your attendance.
<br />
-If you do not have a smartphone or laptop, borrow from a friend or see your instructor.
<br />
-Enter the Attendance Code given out by the instructor for this class session and click Save Code.--%>
</asp:Panel>
<br />
</form>
</body>
</html>cs source
using System;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;public partial class addcourse : System.Web.UI.Page
{protected void Page_LoadComplete(object sender, EventArgs e)
{//MessageBox.Show("You are in the Form.Shown event.");
{
SqlConnection con = new SqlConnection(Database.ConnectionString);
try
{
var returnUrl = Request.Params["ReturnUrl"];
var hostID = Request.Params["HostID"];
if (string.IsNullOrWhiteSpace(hostID))
{
if (!string.IsNullOrWhiteSpace(returnUrl))
Response.Redirect(returnUrl);throw new Exception("Variable \"HostID\" not found in query params");
}con.Open();
var query = @"select distinct u.hostid as StudentID
,u.ID as UserID
,sd.scheduledaysid as CourseID
,sd.status
,sd.minutes
,sm.crs_cde as CourseCode
,sm.SHORT_CRS_TITLE_1 as CourseTitle
,sm.yr_cde
,sm.trm_cde
,sd.startTime AS CourseStartTime
,sd.startTime
,CONCAT(u.LastName, ', ',u.FirstName) AS StudentName
,u.Email
,nm.FIRST_NAME
,nm.MIDDLE_NAME
,CONCAT(nm.LAST_NAME, ', ',nm.FIRST_NAME) AS InstructorName
from ics_net.dbo.LMS_ScheduleDays as sd
inner join ics_net.dbo.lms_section as s on
sd.sectionid = s.SectionID
inner JOIN ics_net.dbo.LMS_Course AS c WITH (NOLOCK) ON s.CourseID = c.CourseID
inner join tmseprd.dbo.section_master as sm on
c.CourseCode + ' ' + s.NAME = sm.crs_cde and
left(s.erpcoursekey,4) = sm.yr_cde and
substring(s.ERPCourseKey,6,2) = sm.trm_cde
inner join tmseprd.dbo.student_crs_hist as sch on
sm.crs_cde = sch.crs_cde and
sm.yr_cde = sch.yr_cde and
sm.trm_cde = sch.trm_cde
inner join ics_net.dbo.fwk_user as u on
sch.id_num = u.hostid
inner join tmseprd.dbo.name_master as nm on
sm.LEAD_INSTRUCTR_ID = nm.id_num
wheresd.startdate <= dateadd(mi, 10, @Now)
and sd.enddate >= @Nowand u.HostID = @HostID
and sm.crs_cde not like 'ONSO%'
AND sm.CRS_CDE NOT LIKE 'CLIN 7303 001'
AND sm.CRS_CDE NOT LIKE 'CLIN 7203 001'
AND sm.CRS_CDE NOT LIKE 'CLIN 8103 001'
and sm.LOC_CDE = 'main'
and sch.TRANSACTION_STS = 'C'
orsd.startdate <= dateadd(mi, 10, @Now)
and sd.enddate >= @Nowand u.HostID = @HostID
and sm.crs_cde not like 'ONSO%'
AND sm.CRS_CDE NOT LIKE 'CLIN 7303 001'
AND sm.CRS_CDE NOT LIKE 'CLIN 7203 001'
AND sm.CRS_CDE NOT LIKE 'CLIN 8103 001'
and sm.LOC_CDE = 'main'
and sch.TRANSACTION_STS = 'C'";var cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("HostID", hostID);
cmd.Parameters.AddWithValue("now", DateTime.Now);string studentId = null, userId = null, studentName = null, courseId = null, courseCode = null, courseTitle = null, courseStartTime = null, instructorName = null;
var reader = cmd.ExecuteReader();
if (reader.Read())
{
studentId = reader["StudentID"].ToString();
userId = reader["UserID"].ToString();
studentName = reader["StudentName"].ToString();
courseId = reader["CourseID"].ToString(); //courseId "86ab3a58-1d7c-4ced-82f9-d7ffacf17421" string
courseCode = reader["CourseCode"].ToString();
courseTitle = reader["CourseTitle"].ToString();
courseStartTime = reader["CourseStartTime"].ToString();
instructorName = reader["InstructorName"].ToString();
}txtCourseCode.Text = courseCode;
txtCourseStartTime.Text = courseStartTime;
txtCourseTitle.Text = courseTitle;
txtInstructorName.Text = instructorName;
txtRecordID.Text = courseId;
txtStudentID.Text = studentId;
txtUserID.Text = userId;
txtStudentName.Text = studentName;
}else
{
lblMsg.Text = "You do not have a class in the next hour.";
//btnUpdate.Enabled = false;
//btnUpdate.Visible = false;
}reader.Close();
}
//catch (Exception ex)
catch (Exception)
{
//lblMsg.Text = "Error --> " + ex.Message;
//lblMsg.Text = "You do not have a class in the next hour.";
}
finally
{
con.Close();
}
}}
protected void btnAdd_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(Database.ConnectionString);
try
{
con.Open(); ////Insert uniqueidentifier for retries
SqlCommand cmd = new SqlCommand("insert into PKRReporting.dbo.attendance(RecordID,StudentID,CourseID,CourseCode,AttendanceCode) values(newid(),@StudentID,@CourseID,@CourseCode,@AttendanceCode)", con); //101292cmd.Parameters.AddWithValue("@RecordID", txtRecordID.Text);
cmd.Parameters.AddWithValue("@StudentID", txtStudentID.Text);
cmd.Parameters.AddWithValue("@CourseID", txtRecordID.Text);
cmd.Parameters.AddWithValue("@CourseCode", txtCourseCode.Text);
cmd.Parameters.AddWithValue("@AttendanceCode", txtAttendanceCode.Text);int count = cmd.ExecuteNonQuery();
if (count == 1)
//lblMsg.Text = "Attendance Code[" + txtCourseCode.Text + "] has been added to log (PKRReporting.dbo.attendance)!"; //record logging of attendance code
lblMsg.Text = "Attendance code logged"; //record logging of attendance code
else
lblMsg.Text = "Could not add code to log"; //showing message if there is some system error, the attendance code does not need to be validated here,var query2 = "select 1 from PKRReporting.dbo.InstructorCourse where CourseCode = @CourseCode and AttendanceCode = @AttendanceCode";
var checkCmd2 = new SqlCommand(query2, con);
checkCmd2.Parameters.AddWithValue("@CourseID", txtRecordID.Text);
checkCmd2.Parameters.AddWithValue("@CourseCode", txtCourseCode.Text);
checkCmd2.Parameters.AddWithValue("@AttendanceCode", txtAttendanceCode.Text);
var reader2 = checkCmd2.ExecuteReader();if (reader2.Read())
{
SqlCommand cmd2 = new SqlCommand("insert into ics_net.dbo.lms_attendance(attendanceID, userid, scheduledaysID, status) values(newid(),CAST(@UserID AS UNIQUEIDENTIFIER),CAST(@CourseID AS UNIQUEIDENTIFIER),'0')", con);
cmd2.Parameters.AddWithValue("@RecordID", txtRecordID.Text); //column was reserved for uniqueidentifier
cmd2.Parameters.AddWithValue("@StudentID", txtStudentID.Text); //needs to be fwk.UserID
cmd2.Parameters.AddWithValue("@UserID", txtUserID.Text);
cmd2.Parameters.AddWithValue("@CourseID", txtRecordID.Text); //scheduledaysID
cmd2.Parameters.AddWithValue("@AttendanceCode", txtAttendanceCode.Text);//attendance code is verified, save
int count2 = cmd2.ExecuteNonQuery();
if (count2 == 1)
lblMsg2.Text = "Attendance saved";
else
lblMsg2.Text = "Attendance not added.";
}
else
{
// attendance code invalid
lblMsg2.Text = "Attendance code invalid.";
}}
//catch (Exception ex)
catch (Exception)
{
//lblMsg2.Text = "Error --> " + ex.Message;
//lblMsg2.Text = "Error --> " + ex.Message + " Identity:" + ;
}
finally
{
con.Close();
}
}
}Thursday, April 25, 2019 8:13 PM
Answers
-
User-893317190 posted
Hi Tom4IT ,
It seems that you will pass HostID as querystring to aspx and don't want to see it in querystring.
If you want to encrypt, you could encrypt your hostid using js and decrypt string to original hostid in c#.
js encode.
function btoaUTF16(sString) { var aUTF16CodeUnits = new Uint16Array(sString.length); Array.prototype.forEach.call(aUTF16CodeUnits, function (el, idx, arr) { arr[idx] = sString.charCodeAt(idx); }); return btoa(String.fromCharCode.apply(null, new Uint8Array(aUTF16CodeUnits.buffer))); } console.log(btoaUTF16("hello")) // result aABlAGwAbABvAA==
C # decode
byte[] data = Convert.FromBase64String("aABlAGwAbABvAA=="); string decodedString = Encoding.UTF8.GetString(data); Response.Write(decodedString);
Please see https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding
But this way is not so secure, you had better not use querysting and try to use form data through post method, then the hostid will not occur in querystring.
Best regards,
Ackerly Xu
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Friday, April 26, 2019 3:18 AM
All replies
-
User-893317190 posted
Hi Tom4IT ,
It seems that you will pass HostID as querystring to aspx and don't want to see it in querystring.
If you want to encrypt, you could encrypt your hostid using js and decrypt string to original hostid in c#.
js encode.
function btoaUTF16(sString) { var aUTF16CodeUnits = new Uint16Array(sString.length); Array.prototype.forEach.call(aUTF16CodeUnits, function (el, idx, arr) { arr[idx] = sString.charCodeAt(idx); }); return btoa(String.fromCharCode.apply(null, new Uint8Array(aUTF16CodeUnits.buffer))); } console.log(btoaUTF16("hello")) // result aABlAGwAbABvAA==
C # decode
byte[] data = Convert.FromBase64String("aABlAGwAbABvAA=="); string decodedString = Encoding.UTF8.GetString(data); Response.Write(decodedString);
Please see https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding
But this way is not so secure, you had better not use querysting and try to use form data through post method, then the hostid will not occur in querystring.
Best regards,
Ackerly Xu
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Friday, April 26, 2019 3:18 AM -
User1045460610 posted
Thanks, do you know if that is AES standard compliant, and uses a SALT?
Friday, April 26, 2019 6:18 PM -
User2038994754 posted
It helps me a lot. I resolve my issues.
Saturday, April 27, 2019 5:40 AM -
User-893317190 posted
Hi Tom4IT ,
If you want to use aes to encrypt in javascript and decrypt in c# , you could refer to the link below.
Also refer to the discussion below.
Best regards,
Ackerly Xu
Monday, April 29, 2019 1:12 AM -
User1045460610 posted
Thanks, I'm not using mvc, just .net framework. Any way to do this without mvc?
Monday, April 29, 2019 1:28 PM -
User475983607 posted
Thanks, I'm not using mvc, just .net framework. Any way to do this without mvc?
Your question is a little confusing.
Your original post has markup which can expose data in clear text. If this is a machine to machine question then HTTPS is fine.
Usually, a POST and HTTPS is used to pass data over an encryption HTTP port. If you wish to further encrypt the HTTP message body then simply do so by picking a method from the standard ASP.NET Cryptography docs.
https://docs.microsoft.com/en-us/dotnet/standard/security/cryptography-model
Monday, April 29, 2019 1:50 PM