密码加密
密码加密
几乎每天笔者们都不得不记住许多不同的密码——信用卡的密码,门禁密码等等。这些密码可以用一种方法记录下来,并且不会被犯罪分子利用吗?
假设我们有一张密码为3451的LISA信用卡,它的密码可以像这样被编码:
a b c d e f g h i j k l m n o p q r s t u v w x y z
1 0 5 3 4 3 2 7 2 5 4 1 9 4 9 6 3 4 1 4 1 2 7 8 5 0 lisa
这样密码就可以写在一张纸上,即使这张纸落在他人手上,密码也是安全的。
我们如何解码信息呢?用来加密密码的密钥是公开的——因此我们可以很容易地读出密码(3451)–试试看!
我们很容易的就可以构造一个用来执行加密的函数encode(Pin,Password)[1]:
encode(Pin, Password) ->
Code = {nil,nil,nil,nil,nil,nil,nil,nil,nil,
nil,nil,nil,nil,nil,nil,nil,nil,nil,
nil,nil,nil,nil,nil,nil,nil,nil},
encode(Pin, Password, Code).
encode([], _, Code) ->
Code;
encode(Pin, [], Code) ->
io:format("Out of Letters~n",[]);
encode([H|T], [Letter|T1], Code) ->
Arg = index(Letter) + 1,
case element(Arg, Code) of
nil ->
encode(T, T1, setelement(Arg, Code, index(H)));
_ ->
encode([H|T], T1, Code)
end.
index(X) when X >= $0, X =< $9 ->
X - $0;
index(X) when X >= $A, X =< $Z ->
X - $A.
我们看一下以下的例子:
> pin:encode("3451","DECLARATIVE").
{nil,nil,5,3,4,nil,nil,nil,nil,nil,nil,1,nil,nil,nil,
nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil}
我们现在使用随机数来替换没有被填充的nil元素:
print_code([], Seed) ->
Seed;
print_code([nil|T], Seed) ->
NewSeed = ran(Seed),
Digit = NewSeed rem 10,
io:format("~w ",[Digit]),
print_code(T, NewSeed);
print_code([H|T],Seed) ->
io:format("~w ",[H]),
print_code(T, Seed).
ran(Seed) ->
(125 * Seed + 1) rem 4096.
然后我们需要一些小函数将所有东西连接在一起:
test() ->
title(),
Password = "DECLARATIVE",
entries([{"3451",Password,lisa},
{"1234",Password,carwash},
{"4321",Password,bigbank},
{"7568",Password,doorcode1},
{"8832",Password,doorcode2},
{"4278",Password,cashcard},
{"4278",Password,chequecard}]).
title() ->
io:format("a b c d e f g h i j k l m \
n o p q r s t u v w x y z~n",[]).
entries(List) ->
{_,_,Seed} = time(),
entries(List, Seed).
entries([], _) -> true;
entries([{Pin,Password,Title}|T], Seed) ->
Code = encode(Pin, Password),
NewSeed = print_code(tuple_to_list(Code), Seed),
io:format(" ~w~n",[Title]),
entries(T, NewSeed).
最后我们可以运行这个程序了:
1> pin:test().
a b c d e f g h i j k l m n o p q r s t u v w x y z
1 0 5 3 4 3 2 7 2 5 4 1 9 4 9 6 3 4 1 4 1 2 7 8 5 0 lisa
9 0 3 1 2 5 8 3 6 7 0 4 5 2 3 4 7 6 9 4 9 2 7 4 9 2 carwash
7 2 2 4 3 1 2 1 8 3 0 1 5 4 1 0 5 6 5 4 3 0 3 8 5 8 bigbank
1 0 6 7 5 7 6 9 4 5 4 8 3 2 1 0 7 6 1 4 9 6 5 8 3 4 doorcode1
1 4 3 8 8 3 2 5 6 1 4 2 7 2 9 4 5 2 3 6 9 4 3 2 5 8 doorcode2
7 4 7 4 2 5 6 5 8 5 8 8 9 4 7 6 5 0 1 2 9 0 9 6 3 8 cashcard
7 4 7 4 2 7 8 7 4 3 8 8 9 6 3 8 5 2 1 4 1 2 1 4 3 4 chequecard
true
之后这些信息可以用很小的字体打印出来,粘在一张邮票的背后,藏在你的领带里面[2]。
