Several problems:
1) Your key names did not match
EncryptByAsymKey(AsymKey_ID('Asym_Password')
DecryptByAsymKey(AsymKey_ID('Asym_Looney_Tunes')
2) Your input and output datatypes don't match up
You are inputing nvarchar (N'password') and trying to get out varchar (CAST(... as VARCHAR))
3) You are truncating the encrypted text and storing it in a less preferrable data type.
try varbinary(8000) since this is what all of the encrypt by functions return
Do a SELECT EncryptByAsymKey(AsymKey_ID('Asym_Password'), 'password'); and see how long the output is (in this case it is 128 bytes long)
Like this:
use master
go
drop database testdb2
go
create database testdb2
go
use testdb2
CREATE TABLE UserLogin
(
Username varchar(25),
Password varbinary(8000)
)
CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'p@ssw0rd';
CREATE ASYMMETRIC KEY Asym_Password
WITH ALGORITHM = RSA_512;
DECLARE @encryptedstuff varbinary(8000);
SELECT @encryptedstuff = EncryptByAsymKey(AsymKey_ID('Asym_Password'), 'password');
INSERT INTO UserLogin
(Username, Password)
VALUES ('admin', @encryptedstuff);
SELECT Username , Password
,DecryptByAsymKey(AsymKey_ID('Asym_Password'), Password)
,CAST(DecryptByAsymKey(AsymKey_ID('Asym_Password') , Password) as VARCHAR)
FROM UserLogin
WHERE CAST(DecryptByAsymKey(AsymKey_ID('Asym_Password'), Password) as VARCHAR) = 'password'
AND Username = 'admin';
David Lundell
Principal Consultant and Trainer
www.mutuallybeneficial.com