RSA {1} RSA Keys: What are dQ, dP and InvQ?
Chinese remainder theory
In this case we generate an RSA key pair. With this we have two prime numbers ( ans ), and compute the modulus (). We then pick ans encryption key value () and than compute , and where . To encrypt a message(), we create a cipher , and than decrypt with . The key pair also includes , and , and these can be used with the Chinese remainder theory to optimize the decryption process.
New two prime numbers and
compute the modules
then pick an encryption exponent such that and then compute:
and where:
The public key is then and the private key is . To encrypt a message , we create a cipher:
and then decrypt with:
The key pair thus contains for a key pair of and .
It also has the values of , and . The values of is:
and is:
and is:
We can use the values of , and to speed up the decryption process. The decryption process is:
To decrypt, we use less complex exponents:
and then we use the Chinese Remainder Theorem to combine the two values:
The recovered message() is then:
from cose.keys.rsa import RSA
from cose.keys.cosekey import CoseKey
import binascii
import Crypto.Util.number
import sys
size=512 # 512-bit keys
msg='hello'
if (len(sys.argv)>1):
size=int(sys.argv[1]) # ValueError: invalid literal for int() with base 10: '--ip=127.0.0.1'
if (len(sys.argv)>2):
msg=str(sys.argv[2])
M= bytes_to_long(msg.encode('utf-8'))
cose_key= RSA.generate_key(size)
print ("\ne=",binascii.hexlify(cose_key.e))
print ("n=",binascii.hexlify(cose_key.n))
print ("d=",binascii.hexlify(cose_key.d))
print ("p=",binascii.hexlify(cose_key.p))
print ("q=",binascii.hexlify(cose_key.q))
print ("dp=",binascii.hexlify(cose_key.dp))
print ("dq=",binascii.hexlify(cose_key.dq))
print ("qinv=",binascii.hexlify(cose_key.qinv))
e=int.from_bytes(cose_key.e,byteorder='big')
d=int.from_bytes(cose_key.d,byteorder='big')
p=int.from_bytes(cose_key.p,byteorder='big')
q=int.from_bytes(cose_key.q,byteorder='big')
N=int.from_bytes(cose_key.n,byteorder='big')
dq=int.from_bytes(cose_key.dq,byteorder='big')
dp=int.from_bytes(cose_key.dp,byteorder='big')
qinv=int.from_bytes(cose_key.qinv,byteorder='big')
c=pow(M,e,N)
m1=pow(c,dp,p)
m2=pow(c,dq,q)
h=(qinv*(m1-m2)) %p
m=(m2+h*q) % (N)
res=long_to_bytes(m)
print (f"\nc: {c} m1: {m1}, m2: {m2}, h: {h}, m: {m}")
print ("Decrypted: ",res.decode())