密码学之RSA

文章引用自泡菜,有兴趣的同学可以看看里面的数学原理。

RSA终端命令

首先要生成一对公钥和秘钥,利用mac自带的openSSL。

1、生成私钥

openssl genrsa -out private.pem 1024
执行结果得到一个private.pem文件

➜  ~ cd Desktop                          
➜  Desktop openssl genrsa -out private.pem 1024
Generating RSA private key, 1024 bit long modulus
......++++++
.++++++
e is 65537 (0x10001)
➜  Desktop

明文查看私钥

openssl rsa -in private.pem -text -out private.txt

➜  Desktop openssl rsa -in private.pem -text -out private.txt
writing RSA key
➜  Desktop cat private.txt 
Private-Key: (1024 bit)
modulus:
    00:c4:8f:af:46:b0:83:c6:b1:4f:36:30:2f:21:b0:(此处省略)
publicExponent: 65537 (0x10001)
privateExponent:
    51:62:68:a1:2d:2e:b2:92:f1:88:2f:35:24:8e:b2:(此处省略)
prime1:
    00:fb:67:9e:d7:60:14:2d:5f:a5:ab:27:1d:84:64:(此处省略)
prime2:
    00:c8:27:70:69:cb:4c:32:fe:d4:f2:20:80:8a:75:(此处省略)
exponent1:
    00:8d:64:d2:ee:38:e8:40:38:aa:19:5f:8f:77:55:(此处省略)
exponent2:
    7a:d8:ba:06:34:e0:ef:eb:b8:87:63:ab:81:4f:f6:(此处省略)
coefficient:
    78:1c:1f:69:c5:4b:58:ed:ad:b0:18:9d:2f:01:72:(此处省略)
-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKBgQDEj7VdnVhocskujLkYlH
(此处省略)
GjnWFHjzeyAlT+54ELndGiaOsqNoyi4gzBXvaiM3Oak=
-----END RSA PRIVATE KEY-----
➜  Desktop 

2、生成公钥,公钥由私钥生成

openssl rsa -in private.pem -pubout -out public.pem
执行结果得到一个public.pem文件

➜  Desktop openssl rsa -in private.pem -pubout -out public.pem
writing RSA key
➜  Desktop 

3、尝试用公钥加密,私钥解密

3.1 创建文本

➜  Desktop vim message.txt
➜  Desktop cat message.txt 
hello
➜  Desktop 

3.2 公钥加密

openssl rsautl -encrypt -in message.txt -inkey public.pem -pubin -out enc.txt
查看加密后的结果是一串乱码

➜  Desktop openssl rsautl -encrypt -in message.txt -inkey public.pem -pubin -out enc.txt
➜  Desktop cat enc.txt 
aJ?gM??N?PB?????,???5?2???l?$/m?(?ј?,j?'?U?α42?Y/S??SL?&cࣙ0F?'g?Qh??Z?)??!??Y(?m???V??7??i???J)?Z??F?d{_R??~Y%                
  ➜  Desktop 

3.3 私钥解密

openssl rsautl -decrypt -in enc.txt -inkey private.pem -out dec.txt
执行结果成功,输出结果与原文一致

➜  Desktop openssl rsautl -decrypt -in enc.txt -inkey private.pem -out dec.txt
➜  Desktop cat dec.txt 
hello
➜  Desktop 

4、证书生成

如果想在代码中实现RSA,需要使用规定格式的证书,而刚才创建的pem格式的证书是不能直接用,要转换成p12、der格式

4.1创建scr证书请求文件

openssl req -new -key private.pem -out rsacert.scr

➜  Desktop openssl req -new -key private.pem -out rsacert.scr
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) []:CN
State or Province Name (full name) []:guangdong
Locality Name (eg, city) []:dongguan
Organization Name (eg, company) []:mumu
Organizational Unit Name (eg, section) []:mumu
Common Name (eg, fully qualified host name) []:mumu
Email Address []:[email protected]

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
➜  Desktop 

4.2签名

openssl x509 -req -days 365 -in rsacert.scr -signkey private.pem -out rsacert.crt
执行结果得到一个有效期365天的crt证书。比如https协议,就是这个文件放在服务器上面,让别人接收。
另外crt也不能直接用,通过它还要转成der和p12

➜  Desktop openssl x509 -req -days 365 -in rsacert.scr -signkey private.pem -out rsacert.crt
Signature ok
subject=/C=CN/ST=guangdong/L=dongguan/O=mumu/OU=mumu/CN=mumu/[email protected]
Getting Private key
➜  Desktop 

4.3转der格式

openssl x509 -outform der -in rsacert.crt -out rsacert.der
执行结果得到rsacert.der文件

➜  Desktop openssl x509 -outform der -in rsacert.crt -out rsacert.der
➜  Desktop 

4.3转p12格式

openssl pkcs12 -export -out p.p12 -inkey private.pem -in rsacert.crt
执行结果得到p.p12文件

➜  Desktop openssl pkcs12 -export -out p.p12 -inkey private.pem -in rsacert.crt
Enter Export Password:
Verifying - Enter Export Password:
➜  Desktop 

代码应用

将上面生成的rsacert.der和p.p12文件拖入工程中,使用现成的加解密工具类文件RSACryptor,代码如下:

    // 加载公钥
    NSString *publick = [[NSBundle mainBundle] pathForResource:@"rsacert.der" ofType:nil];
    [[RSACryptor sharedRSACryptor] loadPublicKey:publick];
    
        
    // 加载私钥
    NSString *private = [[NSBundle mainBundle] pathForResource:@"p.p12" ofType:nil];
    [[RSACryptor sharedRSACryptor] loadPrivateKey:private password:@"111"];
    
    NSString *message = @"hello";
    
    // 加密
    NSData *encryptResult = [[RSACryptor sharedRSACryptor] encryptData:[message dataUsingEncoding:kCFStringEncodingUTF8]];
    NSLog(@"加密结果:\n%@",encryptResult);
    
    // 解密
    NSData *decrypData = [[RSACryptor sharedRSACryptor] decryptData:encryptResult];
    NSString *decryptResult = [[NSString alloc] initWithData:decrypData encoding:kCFStringEncodingUTF8];
    
    NSLog(@"解密结果:\n%@",decryptResult);

输出结果:

RSADEMO[25563:666088] 加密结果:
{length = 128, bytes = 0x8d4feef2 0c555630 1f49eca3 43799757 ... 4ef3e5dd 1813e649 }
RSADEMO[25563:666088] 解密结果:
hello

总结

如果用RSA加密比较大的数据,效率会非常低效,通常会把源数据hash(如md5)一次,再进行RSA加密。
RSA特点:

  • 相对安全,私钥不用传递
  • 效率低
  • 加密数据小

你可能感兴趣的:(密码学之RSA)