Advertisement
Guest User

Untitled

a guest
Sep 7th, 2015
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
J 1.89 KB | None | 0 0
  1. NB. =========================================================
  2. NB.                      RSA
  3. NB. =========================================================
  4. decode=: ((([:>.[^.])#[)#:])
  5. totient=:*/@:(^/*(1:-%@{.))@:(__&q:)
  6. gcd=:+.
  7. NB. binary modular exponentiation
  8. modexp=: verb define
  9.   'm exp n'=.y
  10.   b=.#:exp
  11.   ps=.(m&|@:*:)^:(|.i.#b)n
  12. NB.  ps=.|. 1 ,}. (m&|@:^) scan n,(<:#b)#2
  13.   (m&|@:(*/) * 0&<@:{.@:$) 0-.~ps*b
  14. )
  15. NB. tests stochprim totest
  16. stochprim=: dyad define
  17.   *./1=modexp"_1 y,.(<:y),. ?(x<.y)#y
  18. NB.  (x<.y) -: ((1&=)@:modexp"_1 i. 0:) y,.(<:y),. ?(x<.y)#y
  19. )
  20. NB. tests makeprim bitsize
  21. makeprim=: dyad define
  22.   NB. need to make scale with bit size of prime
  23.   ps=. p:i.65000
  24.   NB. until satisfies x statistical tests
  25.   whilst. -. x stochprim r do.
  26.     NB. use some primes as a heuristic
  27.     whilst. (#ps)>ps(|i.0:)r do.
  28.       NB. make random y bit number with leading 1
  29.       r=.#.x:1,?(<:y)#2
  30.     end.
  31.   end.
  32.   r
  33. )
  34. NB. modular inverse using euclidean algorithm
  35. NB. /slightly/ slower than explicit definition
  36. euclidinvnew=: dyad define
  37.   {.1 (1&{ , (0&{-1&{*<.@:(2&{%3&{)) ,3&{, (2&{-3&{* <.@:(2&{%3&{)) )^:(<:3&{)^:(_) 0 1,x,y
  38. )
  39. NB. modular inverse using euclidean algorithm
  40. euclidinv=: dyad define
  41.   t=.0
  42.   newt=.1
  43.   r=.x NB. modulus
  44.   newr=.y
  45.   while. -. newr-:0 do.
  46.     q=.<.r%newr
  47.     b=.newt
  48.     newt=.t-q*newt
  49.     t=.b
  50.     a=.newr
  51.     newr=.r-q*newr
  52.     r=.a
  53.   end.
  54.   NB. if. r>1 do. error
  55.   if. t<0 do.
  56.     (t+x) return.
  57.   end.
  58.   t
  59. )
  60. NB. modular inverse using modular
  61. NB. exponentiation and totient function
  62. modinv=: dyad define
  63.   modexp x;(<:totient x);y
  64. )
  65. RSAsetup=: verb define
  66.   'p q'=.y
  67.   n=.p*q
  68.   NB. totient of p*q
  69.   totn=.p *&:<: q
  70.   whilst. -.1-:e gcd totn do.
  71.     e=.1+?<:totn
  72.   end.
  73.   d=.totn euclidinv e
  74.   n;e;d
  75. )
  76. RSAencrypt=: dyad define
  77.   'n e d'=.x
  78.   modexp n;e;y
  79. )
  80. RSAdecrypt=: dyad define
  81.   'n e d'=.x
  82.   modexp n;d;y
  83. )
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement