Python + MySQL User encrypted storage verification system

Source: Internet
Author: User
Tags base64 commit decrypt md5 md5 encryption sha1


Python 2.7
IDE Pycharm 5.0.3
Pymysql 0.7.6
MySQL 5.7
MySQL Workbench 6.3

As for how MySQL and Python are used in tandem, see the Python and MySQL linkage example one or two
I'm going to fill in the pits that I dug before. User Storage encryption Verification system Beta online
Landfills & Purpose

This pit is a Python user store encryption and login verification system (Beggar version) dug, then will not use the database, and now learned that not landfills is not very good, is not it?

Application Scenarios

If the database is a temporary third party, and the data stored do not want to let Third-party database administrators see, the message involves privacy, only their own visible, then how to do it, I designed a set of user encryption authentication system, the login password for MD5/SHA1 optional encryption, Encrypt the custom encryption algorithm for plaintext to store. Unable to crack in a short time (private thought)

Characteristics

User encrypted Storage System-for hosting third party databases, content encrypted and stored without secret key cannot be cracked

1. User storage, login, view, delete operations, stored in the database
2. User password encrypted storage, password encryption method optional, at present only optional MD5 and SHA1, user storage content encrypted storage, encryption way to customize
3. Custom (I defined a cryptographic decryption function) encryption sequence, get content no sequence can not decrypt (self-thought)
4. Can change the user password, change the custom key value, change the encrypted storage content
5. Support any digit and form set password, can even set into Chinese! However, please note that it is best to clutter the alphabet mixed, or be cracked first level password, the key value may be exposed!

Implementing the Process Framework


Algorithm flowchart

In fact, the far left of the above flowchart. If the new user and database have the same name, there are two choices, one is renamed, the other is the original user name to modify the password, the line a bit more, too messy even the past, so here omitted, realize the effect please see the following IDE interactive chapters.

Well, the whole frame of mind is like this, of course I didn't think so much at first, just do to do, think of the continuous increase in functionality, more perfect consideration, will add so many options, because of their design, so, inevitably there are flaws, there is no reference to the actual large encryption project how to deal with, next to see.

Implementation code

Here I do not paste the detailed code, too long, estimated three hundred or four hundred lines, I uploaded the source code (with comments) +exe (EXE due to packaging software restrictions can only be used for English character input) +readme (please read), do not need points to download, click here to download the source code
This is just the part of the encryption algorithm that you write. Excuse me!
#自定义加密, decryption algorithm child functions. Combined Base64
def encrypt (key,content): # key: Key, Content: plaintext
S1 = base64.encodestring (str (content)) #将内容进行base64加密
Len1 = Len (key)% 7 #取余数
Len1_list = List_key[len1] #取余数对应list_key中伪码
Mix_first = str (key) +S1 #将key转化为字符串后拼接第一次加密的内容
Mix = len1_list+base64.encodestring (Mix_first) #对拼接后字符串再进行加密, plus a pseudo code

Return mix #存入数据库中, cannot be reversed

def decrypt (Key,mix): # key: Key, Content: redaction

Len2 = Len (key)% 7
Len2_findlist = List_key[len2]

If len2_findlist==mix[0]: #先确定伪码
S2_first = Base64.decodestring (mix[1:]) #反解出第一次的base64编码
S2_second = S2_first[0:len (key)] #获取第一次解出前缀是否为key

If S2_second==str (key): #key值对应了
S2_end = base64.decodestring (S2_first[len (key):]) #反解出去掉前缀后的真实内容的64位编码
print '-------------------------------Validation succeed!-------------------------------'

Return S2_end
Else
Print "warning! Validation failed! Can ' t get Secret words! "

Else
Print "warning! Validation failed! Can ' t get Secret words! "
The explanation is on the above annotation, here to say the implementation effect, in the form of the database should be like this


Database Performance Form

For your own encryption algorithm: Try to write yourself, there will be mistakes in the place, if there is a chance, you can learn cryptography, their contact in the end or too little, just added a pseudo code table, and then two times Base64 encryption, of course, the contents of the database directly to Base64 decoding will not be successful.

The login password is encrypted with MD5/SHA1, and the second layer, after landing, you can select the key value, the input of plaintext encryption, if not my pseudo dictionary and key should not be able to reverse the content of the encryption, so for the database administrator, can not decrypt the contents of the stored database, For special needs of the record or project, I think there should be a place for application.

Interaction effects

This shows the entire IDE interactive interface, and how to handle this;

0. New user registration (you can choose not to set clear text default key is 123456)
-------------------------------Mode Choice-------------------------------------
Store&encrypt-1 login&view&update&delete-2 Quit System-3 Clear Database-4
Select mode:1
-------------------------------Store&encrypt-------------------------------
New USER:K3
Set PASSWORD:K3
-------------------------------Password Encrypt Algorithm-------------------------------------
Md5-1 Sha1-2
Select algorithm:1
1. To set key and plaintext encryption
-------------------------------What ' s Next?-------------------------------------
Store Encrypt Plaintext-1 Maybe Next Time-2
Your choice:1
Please design Your key:k4
Plaintext:k4 ' Secret
#############################################
#SHA1-password&plaintext Encryption succeed!#
#############################################
The following is the default key and clear text setting, select 2 to
-------------------------------What ' s Next?-------------------------------------
Store Encrypt Plaintext-1 Maybe Next Time-2
Your Choice:2
Default KEY ' 123456 '
Default plaintext ' default Storage '
############################################
#MD5-password&plaintext Encryption succeed!#
############################################
2. View encrypted plaintext
(In the No. 0 step, if you do not set the key yourself, there will be a default value for storage)

The following is set for yourself key and clear text (when not set, then key is 123456), view plaintext
-------------------------------K4:what ' s Next?-------------------------------
Update Plaintext-1 View Plaintext-2 update Password-3 update KEY-4 Log out-5 Delete User-6
Your Choice:2
Key:k4
-------------------------------Validation succeed!-------------------------------
Secret Words:k4 ' Secret
Please use your own test in more detail. The code is consistent with the above flowchart.

3. Meet the name of the new user, the solution, modify the password or replace the new names
-------------------------------Mode Choice-------------------------------------
Store&encrypt-1 login&view&update&delete-2 Quit System-3 Clear Database-4
Select mode:1
-------------------------------Store&encrypt-------------------------------
New USER:K1
warning! The Name already exist!
-------------------------------make Your Choice-------------------------------------
Change Password-1 Create New User-2
Select Mode:2
New USER:K2
Set PASSWORD:K3
4. Update login password selection, need to have a previous password, in order to modify
-------------------------------Welcome K1-------------------------------
-------------------------------K1:what ' s Next?-------------------------------
Update Plaintext-1 View Plaintext-2 update Password-3 update KEY-4 Log out-5 Delete User-6
Your Choice:3
Please Enter Original password:k1
Please Enter New password:k2
##########################
#Update Password succeed!#
##########################
5. Update key value
-------------------------------Welcome K1-------------------------------
-------------------------------K1:what ' s Next?-------------------------------
Update Plaintext-1 View Plaintext-2 update Password-3 update KEY-4 Log out-5 Delete User-6
Your Choice:4
Please Enter Original key:k1
Please Enter New key:k2
-------------------------------Validation succeed!-------------------------------
#####################
#Update KEY succeed!#
#####################
6. Update clear Text
-------------------------------K4:what ' s Next?-------------------------------
Update Plaintext-1 View Plaintext-2 update Password-3 update KEY-4 Log out-5 Delete User-6
Your choice:1
Key:k4
-------------------------------Validation succeed!-------------------------------
Original Plaintext:k4 ' secret
New Plaintext:k4 ' s Secret2
###########################
#Update plaintext succeed!#
###########################
Problems encountered and solutions

1.MD5/SHA1 the error caused by different types of encrypted storage.
1. Solution, more try/except use throw errors, positioning errors, commonly used output statements and expected between the error, such as the following, MD5 encryption for the tuple form, and SHA1 for STR type
Import Hashlib

#MD5和SHA1加密算法
def MD5 (STR1):
md = HASHLIB.MD5 ()
Md.update (STR1)
Md_5=md.hexdigest ()
Return Md_5,

def SHA1 (STR1):
SH = HASHLIB.SHA1 ()
Sh.update (STR1)
Sha_1 = Sh.hexdigest ()
Return sha_1

Print MD5 ("123")
Print type (MD5 ("123"))
Print SHA1 ("123")
Print type (SHA1 ("123"))
After running
(' 202cb962ac59075b964b07152d234b70 ',)
<type ' tuple ' >
40bd001563085fc35165329ea1ff5c5ecbdbbeef
<type ' str ' >
Know the appearance of the form, the right remedy on it!

2. Insert, delete, update operation of database, do not change the contents of database
2. Solution, no transaction submitted!
For example, I implement the add operation, and finally I need to add a statement commit
Cur.execute ("INSERT into Store (User_name,passwd,encrypt_words,encrypt_password) VALUES (%s,%s,%s,%s)", (User_name, Passwd,encrypt_str,key_content))

Cur.connection.commit () #commit () Submit things, make changes must commit the transaction, or not update
3. The database appears lock wait timeout exceeded error due to the figure


Cause resolution
&NBSP
3. Solution; This should run the time to disconnect the previous run of the program, which I do not good, debugging, the previous program is still running, all disconnected, as long as a run on the line
 
4. Structural functional Problems
4. The need to practice accumulation, how to achieve the goal, produce a clearer structure, how the child function should be written to the maximum extent of the call, these I am weaker, need to continue to learn and test, my frame structure is also changed a lot of times, have been tested and then slowly modified, taking into account almost all the operational requirements, can you believe that I just want to get a cryptographic write and read the thing on the line, and finally wrote a relatively perfect small project, so, this problem, only keep practicing, but next time I will first frame a flowchart frame to write.  

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.