假设我们有一张密码为3451的LISA信用卡,它的密码可以像这样被编码:
这样密码就可以写在一张纸上,即使这张纸落在他人手上,密码也是安全的。
我们很容易的就可以构造一个用来执行加密的函数encode(Pin,Password):
- 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.
我们看一下以下的例子:
- 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.
然后我们需要一些小函数将所有东西连接在一起:
最后我们可以运行这个程序了:
- 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