-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsubcipher.f90
98 lines (93 loc) · 3.1 KB
/
subcipher.f90
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
module subcipher
implicit none
contains
! map alphabetic characters to 1..26, otherwise to zero
function charcode(c) result(n)
! dummy argument
character, intent(in) :: c
! function result location
integer :: n
! local data
integer :: asc
! processing
asc=iachar(c)
if (asc .ge. 97 .and. asc .le. 122) then
n=asc-96
else if (asc .ge. 65 .and. asc .le. 90) then
n=asc-64
else
n=0
end if
end function
! swap subroutine
subroutine exchange(i, j)
! dummy arguments
integer, intent(inout) :: i, j
! local data
integer :: k
! processing
k=i
i=j
j=k
end subroutine
! shuffle subprogram
subroutine shuffle(n, a)
! dummy arguments
integer, intent(in) :: n
integer, dimension(n), intent(inout) :: a
! local data
integer :: i, idx
real :: r
! processing
do i=1,n-1
call random_number(r)
idx=i+int((n-i)*r)+1
call exchange(a(i), a(idx))
end do
end subroutine
! output characters as text
subroutine teleprinter(n, a)
! dummy arguments
integer, intent(in) :: n
integer, dimension(n), intent(in) :: a
! local data
integer :: i
! processing
print '(72a1)', (achar(64+a(i)),i=1,n)
!print '(5(1x,5a1))', (achar(64+a(i)),i=1,n)
end subroutine
! encrypt plaintext using substitution cipher
function substitution_encrypt(n, plaintext, key) result(ciphertext)
! dummy arguments
integer, intent(in) :: n
integer, intent(in), dimension(n) :: plaintext
integer, intent(in), dimension(26) :: key
! function result location
integer, dimension(n) :: ciphertext
! local data
integer :: i
! processing
do i=1,n
ciphertext(i) = key(plaintext(i))
end do
end function
! decrypt ciphertext using substitution cipher
function substitution_decrypt(n, ciphertext, key) result(plaintext)
! dummy arguments
integer, intent(in) :: n
integer, intent(in), dimension(n) :: ciphertext
integer, intent(in), dimension(26) :: key
! function result location
integer, dimension(n) :: plaintext
! local data
integer :: i
integer, dimension(26) :: invkey
! processing
do i = 1, 26
invkey(key(i)) = i
end do
do i = 1, n
plaintext(i) = invkey(ciphertext(i))
end do
end function
end module