一些加密算法

本文涉及的产品
密钥管理服务KMS,1000个密钥,100个凭据,1个月
简介: 参考文献:https://mp.weixin.qq.com/s?__biz=MzU1MzE3Njg2Mw==&mid=2247485826&idx=1&sn=60126c394a72cd6bfaf31a32bc04dce3&chksm=fbf793f2...

参考文献:https://mp.weixin.qq.com/s?__biz=MzU1MzE3Njg2Mw==&mid=2247485826&idx=1&sn=60126c394a72cd6bfaf31a32bc04dce3&chksm=fbf793f2cc801ae4a85065a45ea6ced1781330f491f430743eebf7f8780e2b5e5a3156d32abf&mpshare=1&scene=23&srcid=1119QvhhqD6IKKZplWqVXRTn#rd

棋盘密码

用一对字母来替代每个明文字母

多文字加密法的密钥是一个5X5的矩阵。这个矩阵的5行和5列用含有5个字母的关键词来标识且该关键词不能有重复的字母。字母表的每一个字母填写在这个矩阵中。矩阵只有25个位置,而字母表有26个字母,因此i和j占同一个单元。这意味着所有j都变成了i。

一个栗子

ilnllliiikkninlekile

长度为20,提示

The length of this plaintext: 10

密文长度是明文的2倍,密文只有5个字母出现,想到多表加密,但不知道表的边缘的排序方式
例如:

  l i n k e 
l a b c d e
i f g h i k
n l m n o p
k q r s t u
e v w x y z

解密脚本

import itertools

key = []
cipher = "ilnllliiikkninlekile"

for i in itertools.permutations('ilnke', 5):
    key.append(''.join(i))

for now_key in key:
    solve_c = ""
    res = ""
    for now_c in cipher:
        solve_c += str(now_key.index(now_c))
    for i in range(0,len(solve_c),2):
        now_ascii = int(solve_c[i])*5+int(solve_c[i+1])+97
        if now_ascii>ord('i'):
            now_ascii+=1
        res += chr(now_ascii)
    if "flag" in res:
        print now_key,res

四方密码

四方密码用4个5×5的来加密。每个矩阵都有25个字母(通常会取消Q或将I,J视作同一样,或改进为6×6的矩阵,加入10个数字)。首先选择两个英文字作密匙,例如examplekeyword。对于每一个密匙,将重复出现的字母去除,即example要转成exampl,然后将每个字母顺序放入矩阵,再将余下的字母顺序放入矩阵,便得出加密矩阵。
将这两个加密矩阵放在右上角和左下角,余下的两个角放a到z顺序的矩阵:

加密的步骤:

  • 两个字母一组地分开讯息:(例如helloworld变成he ll ow or ld)
  • 找出第一个字母在左上角矩阵的位置
  • 找出第二个字母在右下角矩阵的位置
 a b c d e   E X A M P
 f g h i j   L B C D F
 k l m n o   G H I J K
 p r s t u   N O R S T
 v w x y z   U V W Y Z

 K E Y W O   a b c d e
 R D A B C   f g h i j
 F G H I J   k l m n o
 L M N P S   p r s t u
 T U V X Z   v w x y z
img_03dd5c547699d8bf06ae862e2f137884.png
  • 如上图所示,则he加密之后的密文为fy
    加密脚本
#coding:utf-8
import collections
import re

matrix = "ABCDEFGHIJKLMNOPRSTUVWXYZ"
pla = "abcdefghijklmnoprstuvwxyz"
key1 = "[EXAMPL]"
key2 = "[KEYWORD]"
key1 = ''.join(collections.OrderedDict.fromkeys(key1))
key2 = ''.join(collections.OrderedDict.fromkeys(key2))
matrix1 = re.sub('[\[\]]','',key1) + re.sub(key1,'',matrix)
matrix2 = re.sub('[\[\]]','',key2) + re.sub(key2,'',matrix)
matrix_list1 = []
matrix_list2 = []
pla_list = []
for i in range(0,len(matrix1),5):
    matrix_list1.append(list(matrix1[i:i+5]))
for i in range(0,len(matrix2),5):
    matrix_list2.append(list(matrix2[i:i+5]))
for i in range(0,len(pla),5):
    pla_list.append(list(pla[i:i+5]))
def find_index(x):      #查询明文字母位置
    for i in range(len(pla_list)):
        for j in range(len(pla_list[i])):
            if pla_list[i][j] == x:
                return i,j
def gen_cip(letter):
    first = find_index(letter[0]) #两个子母中第一个字母位置
    second = find_index(letter[1])    #两个子母中第二个字母位置
    cip = ""
    cip += matrix_list1[first[0]][second[1]]
    cip += matrix_list2[second[0]][first[1]]
    return cip
def encrypt(pla):
    #pla = "whereismysecretkey"
    cip = ""
    for i in range(0,len(pla),2):
        cip += gen_cip(pla[i:i+2])
    return cip
def main():
    pla = "hello world"
    pla = pla.replace(' ','')
    print encrypt(pla)
if __name__ == "__main__":
    main()

解密脚本

#coding:utf-8
import collections
import re

matrix = "ABCDEFGHIJKLMNOPRSTUVWXYZ"
pla = "abcdefghijklmnoprstuvwxyz"
key1 = "[EXAMPL]"
key2 = "[KEYWORD]"
key1 = ''.join(collections.OrderedDict.fromkeys(key1))
key2 = ''.join(collections.OrderedDict.fromkeys(key2))
matrix1 = re.sub('[\[\]]','',key1) + re.sub(key1,'',matrix)
matrix2 = re.sub('[\[\]]','',key2) + re.sub(key2,'',matrix)
matrix_list1 = []
matrix_list2 = []
pla_list = []
for i in range(0,len(matrix1),5):
    matrix_list1.append(list(matrix1[i:i+5]))
for i in range(0,len(matrix2),5):
    matrix_list2.append(list(matrix2[i:i+5]))
for i in range(0,len(pla),5):
    pla_list.append(list(pla[i:i+5]))
def find_index1(x):        #查询两个密文字母位置
    for i in range(len(matrix_list1)):
        for j in range(len(matrix_list1[i])):
            if matrix_list1[i][j] == x:
                return i,j
def find_index2(y):
    for k in range(len(matrix_list2)):
        for l in range(len(matrix_list2[k])):
            if matrix_list2[k][l] == y:
                return k,l
def gen_pla(letter):
    first = find_index1(letter[0])        #两个子母中第一个字母位置
    second = find_index2(letter[1])     #两个子母中第二个字母位置
    pla = ""
    pla += pla_list[first[0]][second[1]]
    pla += pla_list[second[0]][first[1]]
    return pla
def main():
    cip = "FYHGHZHSJE"
    pla = ""
    for i in range(0,len(cip),2):
        pla += gen_pla(cip[i:i+2])
    print pla
if __name__ == "__main__":
    main()

RSA

题目

#!/usr/bin/python
import random
import string
from hashlib import sha512
from Crypto.Util.number import *
from Crypto.Cipher import AES
import flag
def proof_of_work():
    proof = ''.join([random.choice(string.ascii_letters+string.digits)
                     for _ in xrange(20)])
    digest = sha512(proof).hexdigest()
    print_output("Proof of your work.\nsha512(%s+XXXX) == %s\n" %
                 (proof[:-4], digest))
    print_output('Tell me XXXX:')
    x = raw_input().strip()
    if len(x) != 4 or sha512(proof[:-4]+x).hexdigest() != digest:
        exit(1)
    print_output("OK, you proof.")
    return
def egcd(a, b):
    if (b == 0):
        return 1, 0, a
    else:
        x, y, q = egcd(b, a % b)
        x, y = y, (x - (a // b) * y)
        return x, y, q
def mod_inv(a, b):
    return egcd(a, b)[0] % b
def print_output(message):
    print(message)
    sys.stdout.flush()
def rsa_gen(bit_n=2048, bit_e=64):
    p = getPrime(bit_n/2)
    q = getPrime(bit_n/2)
    n = p*q
    e = getPrime(bit_e)
    d = mod_inv(e, (p-1)*(q-1))
    msg = int(''.join([random.choice(string.ascii_letters+string.digits)
                   for _ in xrange(16)]).encode('hex'), 16)
    cipher = pow(msg, e, n)
    return e, d, n, msg, cipher
def tell_n_d():
    e, d, n, m, c = rsa_gen()
    print_output("Give you a message:0x%x\nand its ciphertext:0x%x" % (m, c))
    print_output("Please give me the private key to decrypt cipher")
    print_output("n:")
    N = int(raw_input().strip())
    print_output("d:")
    D = int(raw_input().strip())
    if not pow(c, D, N) == m:
        exit(1)
    print_output("Oh, how you know the private key!")
    return m
  
def number_theory():
    while True:
        e, d, n, m, c = rsa_gen()
        print_output("n=0x%x\ne=0x%x\nc=0x%x\n" % (n, e, c))
        print_output("Now, you have a chance to decrypt something(but no c):")
        C = int(raw_input().strip())
        if C == c:
            print_output("Nonono~")
            continue
        M = pow(C, d, n)
        print_output("message:0x%x" % M)
        print_output("Give me right message:")
        MM = int(raw_input().strip())
        if not MM == m:
            exit(1)
        print_output("Master in math!")
        return m
        
def pad(s):
    return s + ((16-len(s)%16)*chr(16-len(s)%16))
def handle():
    proof_of_work()
    msg1 = hex(tell_n_d())[2:-1].decode('hex')
    msg2 = hex(number_theory())[2:-1].decode('hex')
    cipher = AES.new(msg2, AES.MODE_CBC, msg1)
    enc = cipher.encrypt(pad(flag.flag))
    print_output("Here is your flag:0x%s" % enc.encode('hex'))
if __name__ == "__main__":
    handle()

解密脚本

from pwn import *
from hashlib import sha512
import string
import gmpy2 as gm

context.log_level = "debug"
sh = remote("106.75.101.197", 7544)
def proof():
    sh.recvline()
    tmp = sh.recv()
    tmp_str = tmp[7:7+16]   
    tmp_sha = tmp[-130:].strip()
    print tmp_str
    print tmp_sha
    sha_dict = string.letters + string.digits 
    for i1 in sha_dict:
        for i2 in sha_dict:
            for i3 in sha_dict:
                for i4 in sha_dict:
                    res = i1+i2+i3+i4
                    if(sha512(tmp_str+res).hexdigest()==tmp_sha):
                        return res
def stage1():
    sh.recvline()
    m_tmp = sh.recvline()
    m = m_tmp[-35:]
    log.success("Get the M: %s" %m)
    sh.recvuntil("ciphertext:")
    c = sh.recv().strip()
    log.success("Get the C: %s" %c)
    # generate the d, n
    m, c = int(m, 16), int(c, 16)
    d = 1
    n = (c - m) / 2
    sh.recvuntil("n:")
    sh.sendline(str(n))
    sh.recvuntil("d:")
    sh.sendline(str(d))
    log.success("---STAGE 1 PASS---\n\n")
def stage2():
    sh.recvuntil("n=")
    n = sh.recvline()
    sh.recvuntil("e=")
    e = sh.recvline()
    sh.recvuntil("c=")
    c = sh.recvline()
    log.success("Get the N: %s" %n)
    log.success("Get the E: %s" %e)
    log.success("Get the C: %s" %c)
    e,n,c = int(e,16), int(n,16), int(c,16)
    sh.recvuntil("no c):")
    y = gm.powmod(2, e, n)
    y = gm.powmod(c*y, 1, n)
    invert_numb = gm.invert(2, n)
    sh.sendline(str(y))
    sh.recvline()
    res =sh.recvline()[8:].strip()
    log.success("Get the Decrypt result: %s", res)
    res = int(res, 16)
    M = gm.powmod(res*invert_numb, 1, n)
    sh.recvline()
    sh.sendline(str(M))
    sh.recv()   
res = proof()
log.success("Get the proof result: %s" %res)
sh.recvline()
sh.sendline(res)
stage1()
stage2()
sh.interactive()
目录
相关文章
|
4月前
|
算法 数据安全/隐私保护
对称密钥加密算法和公开密钥加密算法有什么区别
【4月更文挑战第19天】对称密钥和公开密钥加密算法各有特点:对称密钥加密速度快,适用于大量数据,但密钥管理困难;公开密钥加密安全性高,密钥管理方便,但速度慢,常用于数字签名和身份验证。两者在不同场景下有不同优势。
162 6
|
11月前
|
算法 数据安全/隐私保护 C语言
XXTEA加密算法
XXTEA加密算法
313 0
|
3月前
|
存储 安全 算法
三种常见的加密算法:MD5、对称加密与非对称加密的比较与应用
网络安全聚焦加密算法:MD5用于数据完整性校验,易受碰撞攻击;对称加密如AES快速高效,密钥管理关键;非对称加密如RSA提供身份验证,速度慢但安全。三种算法各有所长,适用场景各异,安全与效率需权衡。【6月更文挑战第17天】
299 2
|
4月前
|
算法 安全 数据安全/隐私保护
公钥密码学:解密加密的魔法世界
【4月更文挑战第20天】
54 2
公钥密码学:解密加密的魔法世界
|
4月前
|
数据采集 算法 安全
加密算法
逆向工程主要关注思维和分析方法,而非仅仅代码。它涉及破解加密数据和处理动态请求参数。常见的加密算法包括线性散列(如MD5)、对称加密(AES, DES)和非对称加密(RSA)。MD5加密是不可逆的,但可通过暴力破解。DES/AES使用相同密钥进行双向加密,而RSA则使用公钥加密,私钥解密。Base64是一种编码而非加密,易于解码。理解加密类型和解密策略是逆向的重点。
38 0
|
存储 算法 安全
几种加密算法
几种加密算法
|
算法 安全 Unix
常见加密算法介绍及比较
常见加密算法介绍及比较
294 0
|
存储 算法 安全
5种常用加密算法!
5种常用加密算法!
|
算法 安全 数据安全/隐私保护
浅谈加密算法 aes
浅谈加密算法 aes
浅谈加密算法 aes
|
数据安全/隐私保护
对称加密及AES加密算法
对称加密及AES加密算法
295 0