CREATE PROCEDURE procCryptPassword
	@strName as varchar(100),
	@strPassword as varchar(100),
	@strCrypt as varchar(100) OUTPUT

AS

declare @intSalt as int,
	@intPassSalt as int,
	@intNameSalt as int,
	@intMaxCounter as int,
	@intCounter as int,
	@intCounter2 as int,
	@intCounter3 as int,
	@intLenName as int,
	@intLenPassword as int,
	@intMaxLen int

/*this is an implementation dependant value that should be arbitrarily changed for each database (but fixed once implemented)*/
set @intSalt = 1010



set @intLenPassword = len(@strPassword)
set @intLenName = len(@strName)

if @intLenPassword = 0 and @intLenName = 0
	return

if @intLenName = 0
	return

/* ensure a minum length of 12 characters by concatenating name and password*/
while (@intLenName < 12)
begin
	select @strName = @strName + @strPassword
	set @intLenName = len(@strName)
	if (@intLenName < 12) 
	begin
		select @strName = @strName + @strName
		set @intLenName = len(@strName)
	end
		
end

while (@intLenPassword < 12) 
begin
	select @strPassword = @strPassword + @strName
	set @intLenPassword = len(@strPassword)
	if (@intLenPassword < 12) 
	begin
		select @strPassword = @strPassword + @strPassword
		set @intLenPassword = len(@strPassword)
	end
		
end

set @strCrypt = ''

select @intCounter = 0, @intMaxCounter = 0, @intCounter2 = 0

/*ensure that the crypt password is as long as the longest input (user/password)*/
if @intLenPassword < @intLenName
	set @intMaxLen = @intLenName
else
	set @intMaxLen = @intLenPassword

while (@intMaxCounter < @intMaxLen)
begin

/*add in a salt from the user name so small changes here make a big change in the result*/
	set @intNameSalt = 0
	set @intCounter3 = 0
	while (@intCounter3 < @intLenName)
	begin
		set @intNameSalt = @intNameSalt + ascii(substring(@strName, @intCounter3 + 1, 1))
						+ ascii(substring(@strPassword, @intCounter + 1, 1))
		set @intCounter3 = @intCounter3 + 1
	end

/*add in a salt from the password so small changes here make a big change in the result*/
	set @intPassSalt = 0
	set @intCounter3 = 0
	while (@intCounter3 < @intLenPassword)
	begin
		set @intPassSalt = @intPassSalt + ascii(substring(@strPassword, @intCounter3 + 1, 1))
		set @intCounter3 = @intCounter3 + 1
	end

	set @strCrypt = @strCrypt + char((((ascii(substring(@strPassword, @intCounter + 1, 1)) 
					+ ascii(substring(@strName, @intCounter2 + 1, 1)))
					+ @intSalt + @intNameSalt + @intPassSalt)%86)+40)

	select @intMaxCounter = @intMaxCounter + 1, @intCounter = @intCounter + 1, @intCounter2 = @intCounter2 + 1
	if (@intCounter2 > @intLenName-1) set @intCounter2 = 0
	if (@intCounter > @intLenPassword-1) set @intCounter = 0

	set @intSalt = @intSalt + 5

end