コード例 #1
0
ファイル: gen_doc.py プロジェクト: netcan/MyCrawler
def gen_doc(db_name='exam_somarx.db', password=None):
    if not os.path.exists('output'):
        os.mkdir('output')
    cipher = DESCipher(password) if password else None
    db = sqlite3.connect(db_name)
    courses = ['mzdsxhzgteshzylltx', 'marxism', 'zgjdsgy', 'sxddxyyfljc']
    # 没有方法的类,只有属性
    Question = namedtuple(
        'Question',
        ['chapter', 'type', 'subject', 'a', 'b', 'c', 'd', 'e', 'answer'])
    sql = 'SELECT chapter, type, subject, a, b, c, d, e, answer FROM {} ORDER BY ABS(chapter), ABS(type);'
    types = [None, '判断题', '单选题', '多选题']
    for course in courses:
        md = ''
        qs = [Question(*q) for q in db.execute(sql.format(course)).fetchall()]
        chapter = -1
        tye = -1

        for q in qs:
            if chapter != int(q.chapter):
                chapter = int(q.chapter)
                md += '## 第 {} 章\n'.format(chapter)
            if tye != q.type:
                tye = q.type
                md += '\n### {}\n'.format(types[tye])
                qid = 1

            md += "{}. {} **{}**\n".format(
                qid,
                (cipher.decrypt(q.subject) if cipher else q.subject).strip(),
                q.answer.replace('0', '错').replace('1', '对')
                if q.answer in '01' else q.answer)
            # 选择题
            if tye != 1:
                md += '```\n'
                for s in list('abcde'):
                    sel = q._asdict()[s]
                    if sel:
                        md += '{}. {}\n'.format(
                            s.upper(),
                            (cipher.decrypt(sel) if cipher else sel).strip())
                md += '```\n'
            qid += 1
            with open('output/{}.md'.format(course), 'w') as f:
                f.write(md)
コード例 #2
0
ファイル: crawler_somarx.py プロジェクト: netcan/MyCrawler
 def __init__(self, password=None, dbname='exam_somarx.db'):
     self.cookies = requests.cookies.RequestsCookieJar()
     # 登陆后,获取session_id,保存id就能保持会话,不需要重复登陆了
     self.cookies.set('ASP.NET_SessionId',
                      '',
                      domain='www.somarx.cn',
                      path='/')
     self.db = sqlite3.connect(dbname)
     self.cipher = DESCipher(password) if password else None
     for table in Exam.chapter_range:
         self.db.execute('''
             CREATE TABLE IF NOT EXISTS "{}"(
             [_id] integer PRIMARY KEY AUTOINCREMENT
             ,[type] INTEGER
             ,[subject] VARCHAR(255) COLLATE NOCASE UNIQUE
             ,[a] VARCHAR(200) COLLATE NOCASE
             ,[b] VARCHAR(200) COLLATE NOCASE
             ,[c] VARCHAR(200) COLLATE NOCASE
             ,[d] VARCHAR(200) COLLATE NOCASE
             ,[e] VARCHAR(200) COLLATE NOCASE
             ,[answer] VARCHAR(200) COLLATE NOCASE
             ,[chapter] VARCHAR(200) COLLATE NOCASE
             );
         '''.format(table))
コード例 #3
0
ファイル: crawler_somarx.py プロジェクト: netcan/MyCrawler
class Exam:
    url = 'http://www.somarx.cn/Chapter/ChapterList'
    headers = {
        'user-agent':
        'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) '
        'Chrome/62.0.3202.75 Safari/537.36 '
    }
    chapter_range = {
        'mzdsxhzgteshzylltx': [],
        'marxism': [],
        'zgjdsgy': [],
        'sxddxyyfljc': []
    }
    course_id = {
        'mzdsxhzgteshzylltx': {
            'courseId': 3
        },
        'marxism': {
            'courseId': 1
        },
        'zgjdsgy': {
            'courseId': 2
        },
        'sxddxyyfljc': {
            'courseId': 4
        }
    }

    def __init__(self, password=None, dbname='exam_somarx.db'):
        self.cookies = requests.cookies.RequestsCookieJar()
        # 登陆后,获取session_id,保存id就能保持会话,不需要重复登陆了
        self.cookies.set('ASP.NET_SessionId',
                         '',
                         domain='www.somarx.cn',
                         path='/')
        self.db = sqlite3.connect(dbname)
        self.cipher = DESCipher(password) if password else None
        for table in Exam.chapter_range:
            self.db.execute('''
                CREATE TABLE IF NOT EXISTS "{}"(
                [_id] integer PRIMARY KEY AUTOINCREMENT
                ,[type] INTEGER
                ,[subject] VARCHAR(255) COLLATE NOCASE UNIQUE
                ,[a] VARCHAR(200) COLLATE NOCASE
                ,[b] VARCHAR(200) COLLATE NOCASE
                ,[c] VARCHAR(200) COLLATE NOCASE
                ,[d] VARCHAR(200) COLLATE NOCASE
                ,[e] VARCHAR(200) COLLATE NOCASE
                ,[answer] VARCHAR(200) COLLATE NOCASE
                ,[chapter] VARCHAR(200) COLLATE NOCASE
                );
            '''.format(table))

    def get_chapter_list(self):
        for course in Exam.course_id:
            if not Exam.chapter_range[course]:
                r = requests.get(Exam.url,
                                 params=Exam.course_id[course],
                                 cookies=self.cookies,
                                 headers=self.headers)
                html = fromstring(r.text)
                Exam.chapter_range[course] = [
                    x.attrib['href'] for x in html.cssselect('.start-do')
                ]

    def crawler(self):
        self.get_chapter_list()
        for course in Exam.chapter_range:
            for cid, chapter in enumerate(Exam.chapter_range[course]):
                r = requests.get(urljoin(self.url, chapter),
                                 cookies=self.cookies,
                                 headers=self.headers)
                html = fromstring(r.text)
                question = [
                    q.text
                    for q in html.cssselect('.question-word > p:nth-child(2)')
                ]
                selection = html.cssselect('ol[type="A"]')
                right_ans = [a.text for a in html.cssselect('b.right-answer')]
                for ques, sel, ra in zip(question, selection, right_ans):
                    if self.cipher:
                        ques = self.cipher.encrypt(ques)

                    if ra in '对错':
                        ra = '1' if ra == '对' else '0'
                    data = {
                        'chapter':
                        str(cid if course != 'mzdsxhzgteshzylltx' else cid +
                            1),
                        'question':
                        ques,  # 题目
                        'answer':
                        ra,
                        'a':
                        str(),
                        'b':
                        str(),
                        'c':
                        str(),
                        'd':
                        str(),
                        'e':
                        str(),
                    }
                    # 1判断 2单选 3多选
                    data['type'] = 1 if data['answer'] in '01' else \
                        2 if len(data['answer']) == 1 else 3
                    try:
                        if data['type'] != 1:
                            for s, sc in zip(list('abcde'),
                                             sel.xpath('li/p/text()')):
                                data[
                                    s] = sc if not self.cipher else self.cipher.encrypt(
                                        sc)
                            self.db.execute(
                                "INSERT INTO {} (type, subject, a, b, c, d, e, answer, chapter) VALUES ("
                                "?, ?, ?, ?, ?, ?, ?, ?, ?) ".format(course),
                                (data['type'], data['question'], data['a'],
                                 data['b'], data['c'], data['d'], data['e'],
                                 data['answer'], data['chapter']))
                        else:
                            self.db.execute(
                                "INSERT INTO {} (type, subject, answer, chapter) VALUES (?, ?, ?, ?)"
                                .format(course),
                                (data['type'], data['question'],
                                 data['answer'], data['chapter']))
                    except IntegrityError:
                        pass
                print('{}第{}章已抓取'.format(course, data['chapter']),
                      len(question), '条')
            print(
                '{}已抓取'.format(course),
                len(
                    self.db.execute(
                        'select * from {}'.format(course)).fetchall()), '条')
            self.db.commit()
コード例 #4
0
ファイル: window.py プロジェクト: divyesh98/SOMeT
def lsbAlgoDefault(encrypt_decrypt, secret_string, encryption_technique):
    # if (algo_technique == technique_options[0]):
    # LSB:: Text Steganography
    if (encrypt_decrypt == options[0]):
        print("LSB:::Text::: Encrypt")
        # Warning for secret string
        if (len(secret_string) == 1):
            print("Empty Secret:: Showing warning")
            tk.messagebox.showwarning(
                "Data Required", "Please enter secret data to be encoded")
            return
        # encoding
        steg = LSBSteg(cv2.imread(image_path))
        file_name = encryption_technique + "Plain.txt"
        text_file = open(file_name, "w")
        text_file.write(str(secret_string))
        text_file.close()
        if encryption_technique == "OTP":
            enc = OneTimePad(secret_string, "Plain")
            enc_string = enc.run(encrypt_decrypt)

        elif encryption_technique == "RSA":
            enc = RSACipher(secret_string, "Plain")
            enc_string = enc.run(encrypt_decrypt)

        elif encryption_technique == "AES":
            enc = AESCipher(secret_string, "Plain")
            enc_string = enc.run(encrypt_decrypt)

        elif encryption_technique == "DES":
            enc = DESCipher(secret_string, "Plain")
            enc_string = enc.run(encrypt_decrypt)

        img_encoded = steg.encode_text(enc_string)
        cv2.imwrite("secret/secret.png", img_encoded)
        displayImage("secret/secret.png")
        img1 = cv2.imread(image_path)
        img2 = cv2.imread("secret/secret.png")
        imgA = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
        imgB = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
        compare_images(imgA, imgB, "LSB", encryption_technique)
    else:
        print("LSB:::Text::: Decrypt")
        # decoding
        print(image_path)
        im = cv2.imread(image_path)
        steg = LSBSteg(im)
        secret = steg.decode_text()

        print("Secret is", secret)

        if encryption_technique == "OTP":
            dec = OneTimePad(secret, "Plain")
            secret_message = dec.run(encrypt_decrypt)

        elif encryption_technique == "RSA":
            dec = RSACipher(secret, "Plain")
            secret_message = dec.run(encrypt_decrypt)

        elif encryption_technique == "AES":
            dec = AESCipher(secret, "Plain")
            secret_message = dec.run(encrypt_decrypt)

        elif encryption_technique == "DES":
            dec = DESCipher(secret, "Plain")
            secret_message = dec.run(encrypt_decrypt)

        filename = encryption_technique + "Plain.txt"
        key_file = open(filename, "r")
        original_message = key_file.readline()
        key_file.close()
        precentage_comparison = compare_strings(original_message,
                                                secret_message)
        print("The strings are equal by", precentage_comparison, "parts")
        addtofile("LSB", encryption_technique[:3], precentage_comparison)
        #dec = OneTimePad(secret, "Plain")
        #secret_message = dec.run(encrypt_decrypt)
        displaySecret(secret_message)
        print("Text value:", secret_message)
コード例 #5
0
ファイル: window.py プロジェクト: divyesh98/SOMeT
def lsbAlgoStegano(type, secret_string, encrypt_decrypt, encryption_technique):
    if (encrypt_decrypt == options[0]):
        if (len(secret_string) == 1):
            print("Empty Secret:: Showing warning")
            tk.messagebox.showwarning(
                "Data Required", "Please enter secret data to be encoded")
            return
    if (type == "DCT"):
        if (encrypt_decrypt == options[0]):
            file_name = encryption_technique + "DCT.txt"
            text_file = open(file_name, "w")
            text_file.write(str(secret_string))
            text_file.close
            if encryption_technique == "OTP":
                enc = OneTimePad(secret_string, "DCT")
                enc_string = enc.run(encrypt_decrypt)

            elif encryption_technique == "RSA":
                enc = RSACipher(secret_string, "DCT")
                enc_string = enc.run(encrypt_decrypt)

            elif encryption_technique == "AES":
                enc = AESCipher(secret_string, "DCT")
                enc_string = enc.run(encrypt_decrypt)

            elif encryption_technique == "DES":
                enc = DESCipher(secret_string, "DCT")
                enc_string = enc.run(encrypt_decrypt)

            outFile = "secret/secretDCT.png"
            x = DCT(image_path)
            secret = x.DCTEn(enc_string, outFile)
            print("secret :: DCT:: ", secret)
            # secret = red.hide(image_path, secret_string)
            # secret.save("secret.png")
            displayImage("secret/secretDCT.png")
            img1 = cv2.imread(image_path, cv2.IMREAD_UNCHANGED)
            print(img1.shape)
            img2 = cv2.imread("secret/secretDCT.png", cv2.IMREAD_UNCHANGED)
            print(img1.shape, img2.shape)
            if is_grey_scale(image_path) and len(img2.shape) == 3:
                imgA = cv2.cvtColor(img1, cv2.COLOR_BGRA2GRAY)
                imgB = cv2.cvtColor(img2, cv2.COLOR_BGRA2GRAY)
            else:
                imgA = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
                imgB = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
            compare_images(imgA, imgB, "DCT", encryption_technique)
        else:
            y = DCT(image_path)
            secret = y.DCTDe()
            # secret = red.reveal(image_path)
            print("Secret is ", secret)
            if encryption_technique == "OTP":
                dec = OneTimePad(secret, "DCT")
                secret_message = dec.run(encrypt_decrypt)

            elif encryption_technique == "RSA":
                dec = RSACipher(secret, "DCT")
                secret_message = dec.run(encrypt_decrypt)

            elif encryption_technique == "AES":
                dec = AESCipher(secret, "DCT")
                secret_message = dec.run(encrypt_decrypt)

            elif encryption_technique == "DES":
                dec = DESCipher(secret, "DCT")
                secret_message = dec.run(encrypt_decrypt)

            #dec = OneTimePad(secret, "DCT")
            #secret_message = dec.run(encrypt_decrypt)
            filename = encryption_technique + "DCT.txt"
            key_file = open(filename, "r")
            original_message = key_file.readline()
            key_file.close()
            precentage_comparison = compare_strings(original_message,
                                                    secret_message)
            print("The strings are equal by", precentage_comparison, "parts")
            addtofile("DCT", encryption_technique[:3], precentage_comparison)
            displaySecret(secret_message)
            saveSecretToFile(secret_message)
コード例 #6
0
def main ( ):
  # check number of parameters
  if len(sys.argv) != 6 and len(sys.argv) != 7 and len(sys.argv) != 8:
    badUser("ERROR: incorrect number of parameters provided\ncheck README")

  cipherName = sys.argv[1]                                  # <CIPHER NAME>
  key = sys.argv[2]                                         # <KEY>
  mode = sys.argv[3]                                        # <ENC/DEC>
  inputFile = sys.argv[4]                                   # <INPUTFILE>
  outputFile = sys.argv[5]                                  # <OUTPUTFILE>

  # deeper check of number of parameters
  if cipherName in {"DESCBC", "RSACBC"}: # set of CBC mode ciphers
    if len(sys.argv) != 7:
      badUser("ERROR: incorrect number of parameters for CBC\ncheck README")
    elif len(sys.argv[6]) != 8:
      badUser("ERROR: IV isn't 8 characters\ncheck README")
    else:
      IV = sys.argv[6] # TODO: 8 character string
  elif cipherName in {"DESCFB", "RSACFB"}: # set of CFB mode ciphers
    if len(sys.argv) != 8:
      badUser("ERROR: incorrect number of parameters for CFB\ncheck README")
    elif len(sys.argv[6]) != 8:
      badUser("ERROR: IV isn't 8 characters\ncheck README")
    else:
      IV = sys.argv[6]
      try: # ensure s is an int
        s = int(sys.argv[7]) #TODO check that it's between 1 and 64
      except ValueError:
        badUser("ERROR: s argument provided couldn't translate to a 10-base int\ncheck README")      
  elif len(sys.argv) != 6:
    badUser("ERROR: incorrect number of parameters for ECB\ncheck README")

  toConvert = readFile(inputFile)                           # attempt to read file
  
  if cipherName in {"DES", "DESCBC", "DESCFB"}:
    cipher = DESCipher()                                       # Create an instance of the class
    if cipher.setKey(key) == False:                            # Attempt to set the key
      badUser("Invalid key for DES Cipher. Key must be 16 hexidecimal characters (0-9, a-f)!")

  elif cipherName in {"RSA", "RSACBC", "RSACFB"}:
    cipher = RSACipher()
    if cipher.setKey(key) == False:                            # Attempt to set the key
      badUser("Setting RSA key failed\ncheck README")

  else:                                                     # Invalid Cipher
    badUser("Invalid <CIPHER NAME>\ncheck README")

  if mode == "ENC":
    print("ENC: Encryption mode selected. Encrypting...")
    if cipherName in {"DESCBC", "RSACBC"}:
      if cipherName == "DESCBC":
        n = 64
      else:
        n = cipher._key.size() # maximum size of text that the key can handle in bits
        IV = strToBinStr(IV)
        IV += IV * (n - len(IV)) # duplicate IV to fit n
        IV = IV[:n] # cut off the extra characters
        IV = strToBinStr(IV)
      converted = encryptCBC(cipher, toConvert, IV, n)
    elif cipherName in {"DESCFB", "RSACFB"}:
      converted = encryptCFB(cipher, toConvert, IV, s)
    else:
      converted = cipher.encrypt(toConvert)                     # Encrypt and receive the ciphered text
#    print("The ciphered text is: {}".format(converted))

  elif mode == "DEC":
    print("DEC: Decryption mode selected. Decrypting...")
    if cipherName in {"DESCBC", "RSACBC"}:
      if cipherName == "DESCBC":
        n = 64
      else:
        n = cipher._key.size() # maximum size of text that the key can handle in bits
        IV = strToBinStr(IV)
        IV += IV * (n - len(IV)) # duplicate IV to fit n
        IV = IV[:n] # cut off the extra characters
        IV = strToBinStr(IV)
      converted = decryptCBC(cipher, toConvert, IV, n)
    elif cipherName in {"DESCFB", "RSACFB"}:
      converted = decryptCFB(cipher, toConvert, IV, s)
    else:
      converted = cipher.decrypt(toConvert)                   # Decrypt and receive the deciphered text
#    print("The deciphered text is: {}".format(converted))
  else:
    badUser("ERROR: please specify <ENC/DEC>")

  writeFile(outputFile, converted)                            # print converted text
コード例 #7
0
DESCRIPTION: Test program for DESCipher class

FILES REQUIRED: CipherInterface.py
				DESCipher.py

PYTHON LILBRARIES REQUIRED : pycrpyto

				$pip install pycrpyto

'''

from CipherInterface import CipherInterface
from DESCipher import DESCipher

myDES = DESCipher()
key = raw_input("Enter the key: ")

if myDES.setKey(key) == False:
    print(
        "Invalid key for DES Block Cipher. Key must be 8 Byte Hexadecimal value"
    )

else:

    msg = raw_input("Enter the message: ")
    print("The key is: ", myDES._key)
    out = myDES.encrypt(msg)
    print("Ciphertext: ")
    print(out)
    decrypted = myDES.decrypt(out)