日期:2014-05-18  浏览次数:20415 次

【交流贴】在SQL SERVER中实现RSA加密算法
2010年的第一个交流贴,详情见我的blog:http://blog.csdn.net/HEROWANG/archive/2010/01/01/5117081.aspx
/***************************************************  

  作者:herowang(让你望见影子的墙)

  日期:2010.1.1

  注: 转载请保留此信息

  更多内容,请访问我的博客:blog.csdn.net/herowang


****************************************************/


在SQL SERVER中实现RSA加密算法

一、RSA算法原理

RSA算法非常简单,概述如下:
找两素数p和q
取n=p*q
取t=(p-1)*(q-1)
取任何一个数e,要求满足e<t并且e与t互素(就是最大公因数为1)
取d*e%t==1
这样最终得到三个数: n d e

设消息为数M (M <n)
设c=(M**d)%n就得到了加密后的消息c 
设m=(c**e)%n则 m == M,从而完成对c的解密。
注:**表示次方,上面两式中的d和e可以互换。

在对称加密中:
n d两个数构成公钥,可以告诉别人;
n e两个数构成私钥,e自己保留,不让任何人知道。
给别人发送的信息使用e加密,只要别人能用d解开就证明信息是由你发送的,构成了签名机制。
别人给你发送信息时使用d加密,这样只有拥有e的你能够对其解密。

rsa的安全性在于对于一个大数n,没有有效的方法能够将其分解从而在已知n d的情况下无法获得e;同样在已知n e的情况下无法求得d。

以上内容出自原文出处http://www.xfocus.net/articles/200503/778.html

二、使用T-SQL实现RSA算法

  --判断是否为素数

if object_id('f_pnumtest') is not null

  drop function f_isPrimeNum

go

create function [dbo].[f_isPrimeNum]

(@p int)

returns bit

begin

  declare @flg bit,@i int

  select @flg=1, @i=2

  while @i<sqrt(@p)

  begin

  if(@p%@i=0 )

  begin

  set @flg=0

  break

  end  

  set @i=@i+1

  end

  return @flg

end

 

--判断两个数是否互素,首先要选取两个互素的数

 

if object_id('f_isNumsPrime') is not null

  drop function f_isNumsPrime

go

create function f_isNumsPrime

(@num1 int,@num2 int)

returns bit

begin

  declare @tmp int,@flg bit

  set @flg=1

  while (@num2%@num1<>0)

  begin

  select @tmp=@num1,@num1=@num2%@num1,@num2=@tmp

  end

  if @num1=1

  set @flg=0

  return @flg

end

 

--产生密钥对

if object_id('p_createKey1') is not null

  drop proc p_createKey1

go

create proc p_createKey1

@p int,@q int

as

begin

  declare @n bigint,@t bigint,@flag int,@d int

  if dbo.f_pnumtest(@p)=0

  begin

  print cast(@p as varchar)+'不是素数,请重新选择数据'

  return

  end

  if dbo.f_pnumtest(@q)=0

  begin

  print cast(@q as varchar)+'不是素数,请重新选择数据'

  return

  end

  print '请从下列数据中选择其中一对,作为密钥'

  select @n=@p*@q,@t=(@p-1)*(@q-1)

  declare @e int

  set @e=2

  while @e<@t

  begin

  if dbo.f_isNUmsPrime(@e,@t)=0

  begin

  set @d=2

  while @d<@n

  begin

  if(@e*@d%@t=1)

  print cast(@e as varchar)+space(5)+cast(@d as varchar)

  set @d=@d+1

  end

  end

  set @e=@e+1