privateKey
,
err
:
=
rsa
.
GenerateKey
(
rand
.
Reader
,
keySize
)
if
err
!=
nil
{
panic
(
err
)
derText
:
=
x509
.
MarshalPKCS1PrivateKey
(
privateKey
)
block
:
=
pem
.
Block
{
Type
:
"rsa private key"
,
Bytes
:
derText
,
file
,
err
:
=
os
.
Create
(
"private.pem"
)
if
err
!=
nil
{
panic
(
err
)
pem
.
Encode
(
file
,
&
block
)
file
.
Close
(
)
publicKey
:
=
privateKey
.
PublicKey
derstream
,
err
:
=
x509
.
MarshalPKIXPublicKey
(
&
publicKey
)
if
err
!=
nil
{
panic
(
err
)
block
=
pem
.
Block
{
Type
:
"rsa public key"
,
Bytes
:
derstream
,
file
,
err
=
os
.
Create
(
"public.pem"
)
if
err
!=
nil
{
panic
(
err
)
pem
.
Encode
(
file
,
&
block
)
file
.
Close
(
)
func
RSAEncrypt
(
plainText
[
]
byte
,
fileName string
)
[
]
byte
{
file
,
err
:
=
os
.
Open
(
fileName
)
if
err
!=
nil
{
panic
(
err
)
fileInfo
,
err
:
=
file
.
Stat
(
)
if
err
!=
nil
{
panic
(
err
)
buf
:
=
make
(
[
]
byte
,
fileInfo
.
Size
(
)
)
file
.
Read
(
buf
)
file
.
Close
(
)
block
,
_
:
=
pem
.
Decode
(
buf
)
pubInterface
,
err
:
=
x509
.
ParsePKIXPublicKey
(
block
.
Bytes
)
pubKey
:
=
pubInterface
.
(
*
rsa
.
PublicKey
)
cipherText
,
err
:
=
rsa
.
EncryptPKCS1v15
(
rand
.
Reader
,
pubKey
,
plainText
)
if
err
!=
nil
{
panic
(
err
)
return
cipherText
func
RSADecrypt
(
cipherText
[
]
byte
,
fileName string
)
[
]
byte
{
file
,
err
:
=
os
.
Open
(
fileName
)
if
err
!=
nil
{
panic
(
err
)
fileInfo
,
err
:
=
file
.
Stat
(
)
if
err
!=
nil
{
panic
(
err
)
buf
:
=
make
(
[
]
byte
,
fileInfo
.
Size
(
)
)
file
.
Read
(
buf
)
file
.
Close
(
)
block
,
_
:
=
pem
.
Decode
(
buf
)
privKey
,
err
:
=
x509
.
ParsePKCS1PrivateKey
(
block
.
Bytes
)
if
err
!=
nil
{
panic
(
err
)
plainText
,
err
:
=
rsa
.
DecryptPKCS1v15
(
rand
.
Reader
,
privKey
,
cipherText
)
if
err
!=
nil
{
panic
(
err
)
return
plainText
func
main
(
)
{
GenerateRsaKey
(
4096
)
src
:
=
[
]
byte
(
" 好好学习,天天向上... 好好学习,天天向上... 好好学习,天天向上... 好好学习,天天向上... 好好学习,天天向上..."
)
cipherText
:
=
RSAEncrypt
(
src
,
"public.pem"
)
plainText
:
=
RSADecrypt
(
cipherText
,
"private.pem"
)
fmt
.
Println
(
string
(
plainText
)
)
myHash
(
)
func
myHash
(
)
{
myHash
:
=
sha256
.
New
(
)
src
:
=
[
]
byte
(
" 好好学习,天天向上... 好好学习,天天向上... 好好学习,天天向上... 好好学习,天天向上... 好好学习,天天向上..."
)
myHash
.
Write
(
src
)
myHash
.
Write
(
src
)
myHash
.
Write
(
src
)
res
:
=
myHash
.
Sum
(
nil
)
myStr
:
=
hex
.
EncodeToString
(
res
)
fmt
.
Printf
(
"%s\n"
,
myStr
)
禁止 学习某地爬虫,知乎爬虫,CSDN 爬虫。
本文,首发在 learnku 社区。
@author
汪春波(
www.shxdledu.cn)
本作品采用
《CC 协议》
,转载必须注明作者和本文链接