RSA 加解密

作者: wyrover | 来源:发表于2016-05-06 15:24 被阅读45次
    • 加密--公钥
    • 解密--私钥
    • 签名--私钥
    • 验证--公钥

    如果使用私钥对数据进行加密的话,加密就没有意义,因为每个人都可以拥有公钥,所以每个人都可以用公钥进行解密。所以,通常使用私钥对摘要进行加密,然后把加密后的摘要追加到明文的后面,再使用对称密钥对明文和摘要进行整体加密。假如a为私钥拥有者,那么接收者b拿到密文后,可以用对称密钥解密,使用公钥对摘要进行解密,通过对比摘要,可以证明密文是否被篡改,也可以证明密文是否来自私钥的拥有者a,这也就是验签。如果b要向a发送消息,可以使用公钥对消息进行加密,因为只有a拥有私钥,所以只有a可以解密。整体来说,通常是,公钥加密、私钥解密。

    公钥与私钥的理解

    • (1)私钥用来进行解密和签名,是给自己用的。
    • (2)公钥由本人公开,用于加密和验证签名,是给别人用的。
    • (3)当该用户发送文件时,用私钥签名,别人用他给的公钥验证签名,可以保证该信息是由他发送的。当该用户接受文件时,别人用他的公钥加密,他用私钥解密,可以保证该信息只能由他接收到。

    密钥对生成

    //generates a private Key with 8196 Bit
    openssl genrsa -out private.pem 8196
    
    //strips out the public key from the private key
    openssl rsa -in private.pem -out public.pem -outform PEM -pubout
    

    加密过程

    生成 AES KEY

    //generate a Radnom 32 Byte (256 Bit) AES Key
    openssl rand -base64 32 -out aesKey.txt
    

    使用 AES 加密文件

    //encryp the file.txt with the generated AES Key to the file.enc
    openssl enc -aes-256-cbc -salt -in file.txt -out file.enc -pass file:./aesKey.txt
    

    使用 RSA 公钥加密 AES Key

    //encrpyt the AES Key with the RSA Public Key
    openssl rsautl -encrypt -inkey public.pem -pubin -in aesKey.txt -out aesKey.txt.crypted
    

    解密过程

    通过 RSA 私钥解密 AES Key

    //decrypt the AES Key with the Private RSA Key
    openssl rsautl -decrypt -inkey private.pem -in aesKey.txt.crypted -out aesKey.txt.decrypted
    

    通过 AES Key 解密文件

    //decrypt the encrypted file with the encrypted AES Key
    openssl enc -d -aes-256-cbc -in file.enc -out file.txt.decrypted -pass file:./aesKey.txt.decrypted
    

    签名过程

    对文件生成签名

    //Generate the signature.txt for the file.txt
    openssl dgst -sha256 -sign private.pem -out signature.txt file.txt 
    

    对文件验签

    openssl dgst -sha256 -verify public.pem -signature signature.txt file.txt
    # in case of success: prints "Verified OK"
    # in case of failure: prints "Verification Failure"
    

    links

    相关文章

      网友评论

        本文标题:RSA 加解密

        本文链接:https://www.haomeiwen.com/subject/pidjrttx.html