Cryptography - Affine encryption

Status
Not open for further replies.

andyfatbastard

Ars Legatus Legionis
21,183
Subscriptor
Hi folks, google has failed me, so I am requesting the assistance of the Ars faithful. I am looking for an algorithm for the decryption of data encoded using an affine cypher.

i.e. E(x) = (ax+b)%n, where a,b&ltn and gcd[a,n)=1. n being the length of the alphabet in question.

is the encryption formula.

I found out that the formula for decryption is:

x = (ainverse.(E(x) - b))%n

But this makes no sense in my head, as E(x)-b could easily be negative, which to me throws out the whole thing. Am I supposed to just cast out the negativity when modding by n?

Also, I have an algorithm for calculating ainverse, but it doesn't seem to work all the time, sometimes it produces wildly negative answers, which make no sense. Will this happen if I try to find ainverse when gcd(a,n) is not 1?

I understand that not everyone is gonna know what I'm on about, but I'm really struggling to get to grips with this, if anyone's done affine decryption before, could they verify what I've found, and dissuage my fears that it's all gonna go pear shaped?
 
I don't have much time to post now, but here we go:
Modulo algebra is circular. If you work modulo 5 (for example), then 2 - 4 = (2 + 5) - 4 = 7 - 4 = 3

There are no negative numbers... -1 = 4, -2 = 3, -3 = 2, ...

I don't know how modulo goes in most language, but to be sure you should add n until your number is positive before you compute %n, otherwise you might end up with a negative answer.

Hope this helped a little :p Oh and I didn't have time to analyze your stuff right now so I'm not sure this applies.

Edit: A little more stuff :p
is -x%n = n-x where x<n?
Not quite. -x % n is n - x when -n <= x < 0
Better yet: -x % n = (n - (x % n)) % n when x < 0 (after 5 edits, still not sure about it) the last %n is only so you don't get n as a result when x is a multiple of n.

[This message was edited by euzeka on October 10, 2001 at 13:10.]
 

andyfatbastard

Ars Legatus Legionis
21,183
Subscriptor
Got it! An extra 10% on top of my crytography mark in my final exam for me! (and no one else!) Peterb is indeed correct, in C++ -x%n will return -x, it was up to me to add n to any negative answers. So % and modulus are not the same.

Also, the inverse algorithm I had was correct, even though it occasionally threw out negative answers. I just used the negative values, and added n to any negative results obtained.

Sw33t!

Thanks for your help, guys.
 
Status
Not open for further replies.