Python Implementation Method for RC4 file encryption

Source: Internet
Author: User
Tags crc32

Python Implementation Method for RC4 file encryption

This article describes how to implement RC4 file encryption in python. Share it with you for your reference. The specific analysis is as follows:

Based on the RC4 stream encryption algorithm, the extended 16*16 S box and 32-byte key are used.

At present, it should be safer.

I just learned python and it's hard to call it.

In addition, it has been implemented in both VC and python. The two platforms can encrypt and decrypt each other, which is very rewarding.

The following is the implementation in python3.0 and needs to be slightly modified under 2.x.

?

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

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

# For python 3.0.

# From Li Bo

Import struct, sys, OS, binascii

"""

RC4 Encryption Algorithm

16*16 S box

Encryption unit: short

"""

Def RC4 (pkey, keylen, pin, dlen ):

N = 65536

S = list (range (N ))

J = 0

For I in range (N ):

J = (j + S [I] + pkey [I % keylen]) % N

Temp = S [I]

S [I] = S [j]

S [j] = temp

I = j = 0

Pout = B''

For x in range (dlen ):

I = I + 1

J = (j + S [I]) % N

Temp = S [I]

S [I] = S [j]

S [j] = temp

Pout + = struct. pack ('h', pin [x] ^ S [(S [I] + S [j]) % N])

Return (pout)

# Bytes-> short

Def Coding (data ):

If (len (data) % 2 ):

Data + = B '\ 0'

Dlen = len (data) // 2

Return (struct. unpack (str (dlen) + 'h', data ))

# Short-> bytes

Def unCoding (data ):

D = B''

For I in range (len (data )):

D + = struct. pack ('h', data [I])

Return (d)

# Generate a 32-byte key

Def CreatKey (Keyt ):

Pl = len (Keyt)

Key = B''

R = 0

For I in range (32 ):

K = (Keyt [r % pl] + I) % 256

Key + = struct. pack ('B', k)

R + = 1

Return Key

# Update a key

Def UpdataKey (Keyt ):

Key = unCoding (Keyt)

# Shift left of Loop

Key = Key [1:] + struct. pack ('B', Key [0])

Tem = 0

# Sum

For I in range (len (Key )):

Tem + = Key [I];

Keyo = B''

# Xor

For I in range (len (Key )):

Keyo + = struct. pack ('B', (Key [I] ^ tem) % 256)

Tem + = Keyo [I]> 3

Tem = tem %256

Return (Coding (Keyo ))

If _ name _ = '_ main __':

# Retrieving input files

If len (sys. argv) = 1:

Filename = input ('source file :')

Else:

Filename = sys. argv [1]

 

Try:

Fin = open (filename, 'rb ')

Except t:

Print ('failed to open the file! ')

Input ()

Sys. exit ()

Print (filename)

# Open an output file

If filename [-4:] = '. RC4 ':

EID = 1

Key = input ('input decryption key: '). encode ()

Ofilename = filename [:-4]

Else:

EID = 2

Key = input ('input encryption key: '). encode ()

Ofilename = filename + '. RC4'

Key = Coding (CreatKey (key ))

Key = UpdataKey (key)

 

# Process duplicate names

While OS. path. exists (ofilename ):

Ofilename = OS. path. dirname (ofilename) + '\ replicase' + OS. path. basename (ofilename)

Fout = open (ofilename, 'wb ')

Print (ofilename)

# Decryption

If eID = 1:

# Read File Length

Filelen = struct. unpack ('I', fin. read (4) [0]

Print ('flielen = ', filelen,' \ n ......')

While 1:

# Read block size

Ps = fin. read (2)

If not ps:

# End of File

Break

Packsize = struct. unpack ('h', ps) [0]

# Read data

Dd = fin. read (packsize)

# Decryption

Dd = Coding (dd)

X = RC4 (key, len (key), dd, len (dd ))

Key = UpdataKey (key)

# Crc

Crc = struct. unpack ('I', fin. read (4) [0]

If binascii. crc32 (x )! = Crc:

Print ('crc32 verification error! ', Crc, binascii. crc32 (x ))

Input ()

Sys. exit ()

Fout. write (x)

# Fill position at the end of Cropping

Fout. truncate (filelen)

# Encryption

Elif eID = 2:

# Obtain the file length

Fin. seek (0, 2)

Filelen = fin. tell ()

Print ('flielen = ', filelen,' \ n ......')

Fin. seek (0, 0)

Fout. write (struct. pack ('I', filelen ))

While 1:

# Read data

Dd = fin. read (1, 65534)

If not dd:

# End of File

Break

# End Filling

Srl = len (dd)

If srl % 2:

Srl + = 1;

Dd + = B '\ 0'

# Crc

Crc = struct. pack ('I', binascii. crc32 (dd ))

# Encrypt data

Dd = Coding (dd)

X = RC4 (key, len (key), dd, len (dd ))

Key = UpdataKey (key)

# Writing files

Fout. write (struct. pack ('h', srl ))

Fout. write (x)

Fout. write (crc)

Fin. close ()

Fout. close ()

Print ('OK! ')

Input ()

I hope this article will help you with Python programming.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.