文章目录
关于RSA
简介
RSA作为著名的非对称加密算法,在计算机世界里有着广泛的应用。
相对于加密和解密都使用同一份秘钥的对称加密,非对称加密将秘钥分为公钥和私钥两种。加密的时候使用私钥进行加密,加密的内容可以使用公钥进行解密,即达到了非对称加密的效果。具体原理就不展开了。
关于PKCS
根据维基百科:
公钥加密标准(Public Key Cryptography Standards, PKCS),此一标准的设计与发布皆由RSA信息安全公司所制定。
PKCS标准有多套,一般以PKCS #X的形式命名(PKCS #1、PKCS #2等)。下文示例代码遵循的是**PKCS #1 v1.5.**标准,在程序中也有体现。
go语言实践
参考例子:Golang RSA加密解密程序 - 云+社区 - 腾讯云 (tencent.com)
go语言里有专门进行RSA相关操作的包crypto/rsa
,我们可以使用它实现RSA加密解密相关的操作。
生成公钥和私钥
使用rsa.GenerateKey
方法生成公钥和私钥:
// GenerateKey generates an RSA keypair of the given bit size using the
// random source random (for example, crypto/rand.Reader).
func GenerateKey(random io.Reader, bits int) (*PrivateKey, error) {
...
}
其中PrivateKey
结构包含了PublicKey
:
// A PrivateKey represents an RSA key
type PrivateKey struct {
PublicKey // public part.
...
}
私钥签名
使用rsa.SignPKCS1v15
方法传入私钥,生成签名。
// SignPKCS1v15 calculates the signature of hashed using
// RSASSA-PKCS1-V1_5-SIGN from RSA PKCS #1 v1.5.
// ...
func SignPKCS1v15(rand io.Reader, priv *PrivateKey, hash crypto.Hash, hashed []byte) ([]byte, error) {
...
}
由注释可知,使用RSASSA-PKCS1-V1_5-SIGN
方法对哈希字符串进行签名。
公钥验证
使用rsa.VerifyPKCS1v15
传入公钥,可对签名进行认证。
// VerifyPKCS1v15 verifies an RSA PKCS #1 v1.5 signature.
// ...
func VerifyPKCS1v15(pub *PublicKey, hash crypto.Hash, hashed []byte, sig []byte) error {
...
}
可以看到和签名的方法是镜像的。
公钥加密
使用rsa.EncryptPKCS1v15
传入公钥和需要加密的数据进行加密。
// EncryptPKCS1v15 encrypts the given message with RSA and the padding
// scheme from PKCS #1 v1.5. The message must be no longer than the
// length of the public modulus minus 11 bytes.
// ...
func EncryptPKCS1v15(rand io.Reader, pub *PublicKey, msg []byte) ([]byte, error) {
...
}
私钥解密
使用rsa.DecryptPKCS1v15
传入私钥,对加密的数据进行解密。
// DecryptPKCS1v15 decrypts a plaintext using RSA and the padding scheme from PKCS #1 v1.5.
// If rand != nil, it uses RSA blinding to avoid timing side-channel attacks.
// ...
func DecryptPKCS1v15(rand io.Reader, priv *PrivateKey, ciphertext []byte) ([]byte, error) {
...
}
与加密的方法是镜像的。
对于私钥,还需要通过x509.MarshalPKCS1PrivateKey
和x509.ParsePKCS1PrivateKey
将私钥和PKCS #1标准格式的秘钥互转,具体实现见示例。
关于JWT
简介
在jwt.go项目里,作者对什么是JWT进行了简短而明确的说明:
JWT.io has a great introduction to JSON Web Tokens.
In short, it’s a signed JSON object that does something useful (for example, authentication). It’s commonly used for
Bearer
tokens in Oauth 2. A token is ma