Showing posts with label storing. Show all posts
Showing posts with label storing. Show all posts

Monday, March 26, 2012

how to encrypt my password or sensitive data before storing them in a database , using SQL

Hi there ,

1. i have a database and i want to encrypt my passwords before storing my records in a database plus i will later on would require to authenticate my user so again i have to encrypt the string provided by him to compare it with my encrypted password in database

below is my code , i dont know how to do it , plz help

2. one thing more i am storing IP addresses of my users as a "varchar" is there a better method to do it , if yes plz help me

try
{
SqlConnection myConnection = new SqlConnection();
myConnection.ConnectionString = ConfigurationManager.ConnectionStrings["projectConnectionString"].ConnectionString;

SqlDataAdapter myAdapter = new SqlDataAdapter("SELECT *From User_Info", myConnection);
SqlCommandBuilder builder = new SqlCommandBuilder(myAdapter);
DataSet myDataset = new DataSet();
myAdapter.Fill(myDataset, "User_Info");

//Adding New Row in User_Info Table
DataRow myRow = myDataset.Tables["User_Info"].NewRow();
myRow["user_name"] = this.user_name.Text;
myRow["password"] = this.password.Text; // shoule be encrypted
//not known till now how to do it

myRow["name"] = this.name.Text;
myRow["ip_address"] = this.ip_address.Text;

myDataset.Tables["User_Info"].Rows.Add(myRow);
myAdapter.Update(myDataset, "User_Info");

myConnection.Close();
myConnection.Dispose();

}
catch (Exception ex)
{
this.error.Text = "Error ocurred in Creating User : " + ex.Message;
}

Hello my friend, I will give you the answer to this.

Firstly, run the following SQL to create the encrypt function: -

CREATE FUNCTION fn_AlterString
(
@.String AS VARCHAR(800),
@.Key AS VARCHAR(80),
@.Direction AS BIT
)

RETURNS VARCHAR(800)

AS

BEGIN

DECLARE @.NewString AS VARCHAR(800)
SET @.NewString = ''

DECLARE @.Keyi AS INT
SET @.Keyi = 1

DECLARE @.i AS INT
SET @.i = 1

WHILE @.i <= LEN(@.String)
BEGIN
IF (@.Direction = 1)
BEGIN
SET @.NewString = @.NewString + CHAR(ASCII(SUBSTRING(@.String, @.i, 1))
+ CAST(SUBSTRING(@.Key, @.Keyi, 1) AS INT))
END
ELSE BEGIN
SET @.NewString = @.NewString + CHAR(ASCII(SUBSTRING(@.String, @.i, 1))
- CAST(SUBSTRING(@.Key, @.Keyi, 1) AS INT))
END

IF @.Keyi < LEN(@.Key)
BEGIN
SET @.Keyi = @.Keyi + 1
END
ELSE BEGIN
SET @.Keyi = 1
END

SET @.i = @.i + 1
END

RETURN @.NewString

END

Now run the following SQL that will create a stored procedure that your web page will use: -

CREATE PROCEDURE usp_InsertUser
(
@.UserName AS VARCHAR(50),
@.Password AS VARCHAR(50),
@.Key AS VARCHAR(80)
)

AS

INSERT INTO User_Info
( [User_Name],
[Password]
)
VALUES
( @.UserName,
dbo.fn_AlterString(@.Password, @.Key, 1)
)

RETURN

Now alter your web page code as follows: -

SqlConnection

conn =newSqlConnection(ConfigurationManager.ConnectionStrings["projectConnectionString"].ConnectionString);SqlCommand cmd =newSqlCommand("usp_InsertUser", conn);

cmd.CommandType =

CommandType.StoredProcedure;// change these as you see fit

cmd.Parameters.Add(

"@.UserName","test");

cmd.Parameters.Add(

"@.Password","havinggoodday");// ideally, this key should be stored in the web.config file

cmd.Parameters.Add(

"@.Key","564335567754326769012342896");

cmd.ExecuteNonQuery();

conn.Close();

Now for an explanation. The fn_AlterString() function takes a string and transforms it into another based on the second parameter, the key. The third parameter is 1 to encrypt and 0 to decrypt.

Therefore: -

SELECT dbo.fn_AlterString('havinggoodday', '564335567754326769012342896', 1) gives you mgzlqlluvkie|

SELECT dbo.fn_AlterString('mgzlqlluvkie|', '564335567754326769012342896', 0) gives you havinggoodday

You will need to do the latter when checking the password of the user when they log in.

Obviously you will need to use the same key when encrypting and decrypting. They key can only contain numbers. The more digits, the more secure. You can have a larger key than the one used but I put an 80 limit in the function parameter, which you can extend. The key is passed to the stored procedure and in turn passed to the function then used within it, so if somebody stole your database data, your stored procedure code and function code they still would not be able to read your encrypted data because they would need the key, which I suggest you put in the web.config file.

As for your second question, using a varchar to store an ip address is fine. If you need any more help, let me know.

Kind regards

Scotty

|||

hi thanks for your kind help ,

i haven't seen anyone that cool to write an entire code for somebody for free , i appreciate that

one more thing :

can you please tell me how to store and retrieve the key for encryption from web.config file

best regards

gurpreet

|||

Hi Gurpreet,

Within the web.config file add the following within the appSettings section: -

<

appSettings>

<

addkey="VisitationsExpected"value="45545454545445544554"/>

</

appSettings>

Notice the name I have chosen? Call it anything but decryption key. Then within your page code: -

string

strKey =ConfigurationSettings.AppSettings["VisitationsExpected"];

Thanks for the appreciation. I do not appreciate it when users leave one line answers and expect you to know what they mean exactly to fit your situation. I like to take a task to completion. All I ask is that you mark me as the answerer for your question. If you have any more problems, put them in the forum and send me a private message so I am made aware of it.

Kind regards

Scotty

sql

How to encrypt a column(field in a table) in MS SQL 2000

Hi,
I want to store user-id and passwords in a table in SQL Server. But as passwords are very secure, I want to encrypt them while storing and may be decrypt them when reqd.
How can I achieve this functionality
Thanks
-Sudhakarpublic key encryption. it is not built into sql2k. google it.|||It is unnecessary to decrypt passwords.
Store the encrypted string in the database. When someone submits a passwords for authentication, encrypt it using the same algorithm and compare the results with what is stored in the database.
This is called one-way encryption, and is both much simpler and much more secure than two-way encryption. I have a one-way encryption algorithm you can use if you want it.sql

Friday, March 23, 2012

How to enable fast graph operation in sql server?

Storing large graph in

relational form doesn't allow us to perform graph operations such as

shortest path quite efficiently. I'm wondering if storing the graph as

objects would be better? How should I design the schema? Thanks!

Two books:

Inside Microsoft SQL Server 2005: T-SQL Querying by Itzik Ben-Gan

and

Trees and Hierarchies in SQL for Smarties by Joe Celko

have useful information on representing graphs in databases including DDL and DML.

|||Are you basically talking about the classic "traveling salesman" problem?sql

How to enable fast graph operation in sql server?

Storing large graph in

relational form doesn't allow us to perform graph operations such as

shortest path quite efficiently. I'm wondering if storing the graph as

objects would be better? How should I design the schema? Thanks!

Two books:

Inside Microsoft SQL Server 2005: T-SQL Querying by Itzik Ben-Gan

and

Trees and Hierarchies in SQL for Smarties by Joe Celko

have useful information on representing graphs in databases including DDL and DML.

|||Are you basically talking about the classic "traveling salesman" problem?

Friday, March 9, 2012

How to download a file from SQL Server in my Web APP

Hello people,

Do you know how can do for downloading a file stored in a database?. I'm using a table with a FILE field for storing the file.

I know i have to create a special aspx page for downloading, that receives parameters to locate the proper record in the table and then retrieve the file in memory to start downloading.

I have done this with file located at specific folders but not a database's field.

Another thing... the file may be big.

Dou you have any idea about retrieving from sql and sending the file back to the final user?

I really appreciate your support.

Larry.Here's 2 articles, the first is for smaller files, the second is more complicated but better for larger files:

http://support.microsoft.com/kb/316887

http://support.microsoft.com/default.aspx?scid=kb;en-us;317043

Wednesday, March 7, 2012

How to do this in SQL Server Stored Procedure

Here is my problem:

I am designing Support System. I have a stored procedure for storing new Support Ticket. This stored procedure internally gets next ticket number and inserts Support Ticket

CREATE PROCEDURE [sp_SaveSupportTicket]
(
@.pid int,
@.uidGen int,
@.status VarChar (100),
@.probDes text,
@.probSol text,
@.guestName VarChar (100),
@.os VarChar (100),
@.roomNum VarChar (100)
)
AS
DECLARE @.ticNum int
SELECT @.ticNum = MAX(ticNum) + 1 FROM sup_TicDetails
INSERT INTO sup_TicDetails ( ticNum, pid, uidGen, status, probDes, probSol, guestName, os, roomNum,dateofsub)
VALUES (@.ticNum, @.pid, @.uidGen, @.status, @.probDes, @.probSol, @.guestName, @.os, @.roomNum, CONVERT(VARCHAR,GETDATE(),101))
GO

Now... before this happens, on my ASP.NET Page I have a label Ticket# . This label displays next ticket number

CREATE PROCEDURE [sp_GetNextTicketNumber] AS
SELECT max (ticNum) + 1
FROM sup_TicDetails
GO

Now.. how can I have only 1 stored Procedure so that I can obtain next ticket number and display it on ASP.NET page and when I hit "Submit Ticket" sp_SaveSupportTicket gets executed ??

I hope I have made my problem clear !! If not let me know......What you are doing will fail under load. BEtween the time you get the ticket number and insert, another thread could have inserted that same number. Why not use an IDENTITY column? Is it really essential to have the ticket number before you actually save it?|||I see what you are saying !!! no its not necessary to get ticket number before I save it.. it is just to display purpose.

There are problems with identity column ( I read in couple of aticles) so, I am not using Identity column..

Ok, if I don't display ticket number before saving it on my ASP.NET page.. will it still fail while load ??

How to handle thread part !!!!|||I have not heard of the problems you describe with Identity columns. They are certainly more reliable than what you have done here. Even if you do not display the number first, what you are doing will be prone to failure if multiple users are hitting the stored procedure at once. Trust me, Identity is the answer, and then use Scope_Identity() to get the new ID created right after an insert.|||Read this...

http://www.sqlteam.com/item.asp?ItemID=102

Note that if you delete row/s in a table and start adding row/s, the identity column will pick up where it left off.

If I delete a ticket, or try to rollback, I will in problem with Identity column...|||Here is link on MS Website describing Identity Column problem

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/tsqlref/ts_ia-iz_3iex.asp

In our case, I am not sure, but we might have to delete some tickets and than I will be in trouble when I run Reporting Query !!!!!|||After talking to you I me and my friend tried ...

We both saw Ticket# 617 on our ASP.NET display page...

After entering data and hitting "submit", we went into Database to see what happend.

We saw 2 tickets Ticket# 617 created by me and 618 created by him.

So I guess concurrent access didn't gave us problem for insertion.. it displays wrong ticket number on screen ....

I guess I should remove Ticket# from screen than !!!!!!!!!!!

Any other idea ...|||The problem is that you may not be able to duplicate it at will, but the code you are using CAN fail if the two request come in at EXACTLY the same moment.|||Ok.. douglas

I gave you reason why I am not using Identity Column and I told you what happened when we submitted tickets.

I am understanding what you are saying.. .so what is the solution ? What are the chances that both tickets arriave to database at exactly same time ? What happens in that case ?

How can I handle this issue ? Everyone who is developing Web Applications might be running into same issues, how they are handling this or how are you handling such problem ?|||I use Identity columns as meaningless keys to link various rows in a database. It would not bother me if a row was deleted, because I would never rely on these numbers to know how many tickets were outstanding. I would use a SQL Query, not rely upon the ID number of the row. This matches what you would do in a system of paper tickets, because if a ticket is discarded, you would void the ticket and not reuse that number.

How often will folks have a problem with duplicate ticket numbers? Hard to say. You could use some sorts of locking inside of transactions. This is not something I would normally do, and it will serialize this section of code, meaning that only a single user at a time will be able to get to this section of code.|||hummm... Thats interesting !!!! If that is the case how will you set up primary key in your table ?

Here is structure of my table:

ticNum int 4 (primary key) (not auto generated, not identity)
pid int 4 (Property ID Referes to Property Table Primary Key)
uidGen int 4 (UserID Referes to User table Primary Key)
status varchar100
probDes text 16
probSol text 16
guestName varchar100
os varchar100
roomNum varchar100
dateofsub smalldatetime4|||Here is what I found out.. I have total 614 tickets, but when I do SELECT COUNT(*) from sup_TicDetails I see 614. I scanned my records and found that Tic# 100 and 472 are missing.

So I guess my previous developer might be using Identity. I removed Identity column after reding 2 articles i mentioned.

if I try convert primary key into Identity column now, will I be having any problem ?

How can I reset my Identity column every once in a while to fill out gaps or is it Ok to Have Column as identity & primary key and have gap in it ??|||It causes NO PROBLEM AT ALL to have gaps in the numbers.|||So, how you do testing of your code ?Everytime I Add/delete I am going to create gaps and when I transfer that on my production system, I am going to have gap tooo.....

How do I handle database on local system and on production system ?|||This is never something that has been an issue for me...