RSA算法初探

RSA算法


最近在学习支付宝的支付方式,在支付宝接口开发中,用到了RSA加密的方式来加密,于是就对其感兴趣,于是参考网上的RSA算法,结合密码学,于是写出了这篇文章,本文不涉及到任何数学知识,只教你会用。

1. 公钥 私钥的概念

公钥就是大家都能看得到的密钥,也就是我们使用这个密钥来对文本进行加密,假设喜洋洋将hello发给灰太狼,首先喜洋洋用公钥对hello进行加密,一般对ascii码来进行操作,设加密后为¥%#@!&……%,当然了,有人会截取到这段加密后的文字,但不知道什么意思,当灰太狼拿到这个文字,使用私钥进行解密,因为私钥只有灰太狼有,所以只有灰太狼才能知道这段文字是什么意思!

2. 实战

首先我们要构造公钥和私钥

import random,sys,os,rabinMiller
from rabinMiller import gcd,findModInverse

def generateKey(keysize=2048):
    #############################
    p = rabinMiller.generateLargePrime(keysize)
    q = rabinMiller.generateLargePrime(keysize)
    n = p*q
    ################################
    while True:
        e = random.randrange(2**(keysize-1),2**keysize)
        if gcd(e,(p-1)*(q-1)) == 1:
            break
    ################################
    d = findModInverse(e,(p-1)*(q-1))
    ################################
    public_key = (n,e)
    private_key = (n,d)
    return (public_key,private_key)

其中所需要的文件为:

# Primality Testing with the Rabin-Miller Algorithm
# http://inventwithpython.com/hacking (BSD Licensed)

import random


def rabinMiller(num):
    # Returns True if num is a prime number.

    s = num - 1
    t = 0
    while s % 2 == 0:
        # keep halving s while it is even (and use t
        # to count how many times we halve s)
        s = s // 2
        t += 1

    for trials in range(5): # try to falsify num's primality 5 times
        a = random.randrange(2, num - 1)
        v = pow(a, s, num)
        if v != 1: # this test does not apply if v is 1.
            i = 0
            while v != (num - 1):
                if i == t - 1:
                    return False
                else:
                    i = i + 1
                    v = (v ** 2) % num
    return True


def isPrime(num):
    # Return True if num is a prime number. This function does a quicker
    # prime number check before calling rabinMiller().

    if (num < 2):
        return False # 0, 1, and negative numbers are not prime

    # About 1/3 of the time we can quickly determine if num is not prime
    # by dividing by the first few dozen prime numbers. This is quicker
    # than rabinMiller(), but unlike rabinMiller() is not guaranteed to
    # prove that a number is prime.
    lowPrimes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997]

    if num in lowPrimes:
        return True

    # See if any of the low prime numbers can divide num
    for prime in lowPrimes:
        if (num % prime == 0):
            return False

    # If all else fails, call rabinMiller() to determine if num is a prime.
    return rabinMiller(num)


def generateLargePrime(keysize=1024):
    # Return a random prime number of keysize bits in size.
    while True:
        num = random.randrange(2**(keysize-1), 2**(keysize))
        if isPrime(num):
            return num

def gcd(a, b):
    while a != 0:
        a, b = b % a, a
    return b


def findModInverse(a, m):
    # Returns the modular inverse of a % m, which is
    # the number x such that a*x % m = 1

    if gcd(a, m) != 1:
        return None # no mod inverse if a & m aren't relatively prime

    # Calculate using the Extended Euclidean Algorithm:
    u1, u2, u3 = 1, 0, a
    v1, v2, v3 = 0, 1, m
    while v3 != 0:
        q = u3 // v3 # // is the integer division operator
        v1, v2, v3, u1, u2, u3 = (u1 - q * v1), (u2 - q * v2), (u3 - q * v3), v1, v2, v3
    return u1 % m

学过基本数学的话,这段代码还是能够看得懂得。

下面我们就来加密解密了。

message = 'hello' #我要加密的文字
"""plaintext^e mod n"""
public_key, private_key = generateKey() #构造私钥公钥
n,e = public_key
n,d = private_key
"""encrypt = plaintext ^ e % n"""
encrytext = [pow(ord(x),e,n) for x in message]
print(encrytext)
"""plaintext = encrypt ^ d % n"""
dencrypt = [chr(pow(x,d,n)) for x in encrytext]
dencrypt = ''.join(dencrypt)
print(dencrypt)

我们就简单地使用一下这个RSA算法,具体细节并没有深究,需要了解的同学可以网上了解一下。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值