[TOC]
# 非對稱加解密
## 密鑰生成流程
- 生成私鑰操作流程概述
> 1. 使用rsa中的GenerateKey方法生成私鑰
>
> func GenerateKey(random io.Reader, bits int) (priv *PrivateKey, err error)
>
> - rand.Reader -> import "crypto/rand"
> - 1024 的整數倍 - 建議
>
> 2. 通過x509標準將得到的ras私鑰序列化為ASN.1 的 DER編碼字符串
>
> func MarshalPKCS1PrivateKey(key *rsa.PrivateKey) []byte
>
> 3. 將私鑰字符串設置到pem格式塊中
>
> 初始化一個pem.Block塊
>
> ```go
> type Block struct {
> Type string // 得自前言的類型(如"RSA PRIVATE KEY")
> Headers map[string]string // 可選的頭項
> Bytes []byte // 內容解碼后的數據,一般是DER編碼的ASN.1結構
> }
> ```
>
> 4. 通過pem將設置好的數據進行編碼, 并寫入磁盤文件中
>
> func Encode(out io.Writer, b *Block) error
>
> - out - 準備一個文件指針
- 生成公鑰操作流程
> 1. 從得到的私鑰對象中將公鑰信息取出
>
> ```go
> type PrivateKey struct {
> PublicKey // 公鑰
> D *big.Int // 私有的指數
> Primes []*big.Int // N的素因子,至少有兩個
> // 包含預先計算好的值,可在某些情況下加速私鑰的操作
> Precomputed PrecomputedValues
> }
> ```
>
> 2. 通過x509標準將得到 的rsa公鑰序列化為字符串
>
> ```
> func MarshalPKIXPublicKey(pub interface{}) ([]byte, error)
> ```
>
> 3. 將公鑰字符串設置到pem格式塊中
>
> type Block struct {
> Type string // 得自前言的類型(如"RSA PRIVATE KEY")
> Headers map[string]string // 可選的頭項
> Bytes []byte // 內容解碼后的數據,一般是DER編碼的ASN.1結構
> }
>
> 4. 通過pem將設置好的數據進行編碼, 并寫入磁盤文件
>
> func Encode(out io.Writer, b *Block) error
## RSA加解密
### RSA加密
> 1. 將公鑰文件中的公鑰讀出, 得到使用pem編碼的字符串
>
> -- 讀文件
>
> 2. 將得到的字符串解碼
>
> -- pem.Decode
>
> 3. 使用x509將編碼之后的公鑰解析出來
>
> -- func ParsePKCS1PrivateKey(der []byte) (key *rsa.PrivateKey, err error)
>
> 4. 使用得到的公鑰通過rsa進行數據加密
>
### RSA解密
> 1. 將私鑰文件中的私鑰讀出, 得到使用pem編碼的字符串
> 2. 將得到的字符串解碼
> 3. 使用x509將編碼之后的私鑰解析出來
> 4. 使用得到的私鑰通過rsa進行數據解密
## 使用
~~~
import (
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"encoding/hex"
"encoding/pem"
"fmt"
"os"
)
// 生成rsa的密鑰對, 并且保存到磁盤文件中
func GenerateRsaKey(keySize int) {
// 1. 使用rsa中的GenerateKey方法生成私鑰
privateKey, err := rsa.GenerateKey(rand.Reader, keySize)
if err != nil {
panic(err)
}
// 2. 通過x509標準將得到的ras私鑰序列化為ASN.1 的 DER編碼字符串
derText := x509.MarshalPKCS1PrivateKey(privateKey)
// 3. 要組織一個pem.Block(base64編碼)
// 里面還有個Headers屬性可以寫可以不寫
block := pem.Block{
Type : "rsa private key", // 這個地方寫個字符串就行
Bytes : derText,
}
// 4. pem編碼
file, err := os.Create("private.pem")
if err != nil {
panic(err)
}
pem.Encode(file, &block)
file.Close()
// ============ 公鑰 ==========
// 1. 從私鑰中取出公鑰
publicKey := privateKey.PublicKey
// 2. 使用x509標準序列化
derstream, err := x509.MarshalPKIXPublicKey(&publicKey)
if err != nil {
panic(err)
}
// 3. 將得到的數據放到pem.Block中
block = pem.Block{
Type : "rsa public key", // 這個地方寫個字符串就行
Bytes : derstream,
}
// 4. pem編碼
file, err = os.Create("public.pem")
if err != nil {
panic(err)
}
pem.Encode(file, &block)
file.Close()
}
// RSA 加密, 公鑰加密
func RSAEncrypt(plainText []byte, fileName string) []byte{
// 1. 打開文件, 并且讀出文件內容
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()
// 2. pem解碼
block, _ := pem.Decode(buf)
pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
//斷言類型轉換
pubKey := pubInterface.(*rsa.PublicKey)
// 3. 使用公鑰加密
cipherText, err := rsa.EncryptPKCS1v15(rand.Reader, pubKey, plainText)
if err != nil {
panic(err)
}
return cipherText
}
// RSA 解密
func RSADecrypt(cipherText []byte, fileName string) []byte{
// 1. 打開文件, 并且讀出文件內容
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()
// 2. pem解碼
block, _ := pem.Decode(buf)
privKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
panic(err)
}
// 3. 使用私鑰解密
plainText, err := rsa.DecryptPKCS1v15(rand.Reader, privKey, cipherText)
if err != nil {
panic(err)
}
return plainText
}
//測試文件
func main() {
GenerateRsaKey(4096)
src := []byte("abc abc...")
cipherText := RSAEncrypt(src, "public.pem")
plainText := RSADecrypt(cipherText, "private.pem")
fmt.Println(string(plainText))
myHash()
myHash()
}
// 使用sha256
func myHash() {
// sha256.Sum256([]byte("hello, go"))
// 1. 創建哈希接口對象
myHash := sha256.New()
// 2. 添加數據
src := []byte("123 123...")
myHash.Write(src)
myHash.Write(src)
myHash.Write(src)
// 3. 計算結果
res := myHash.Sum(nil)
// 4. 格式化為16進制形式
myStr := hex.EncodeToString(res)
fmt.Printf("%s\n", myStr)
}
~~~
- 基礎
- 簡介
- 主要特征
- 變量和常量
- 編碼轉換
- 數組
- byte與rune
- big
- sort接口
- 和mysql類型對應
- 函數
- 閉包
- 工作區
- 復合類型
- 指針
- 切片
- map
- 結構體
- sync.Map
- 隨機數
- 面向對象
- 匿名組合
- 方法
- 接口
- 權限
- 類型查詢
- 異常處理
- error
- panic
- recover
- 自定義錯誤
- 字符串處理
- 正則表達式
- json
- 文件操作
- os
- 文件讀寫
- 目錄
- bufio
- ioutil
- gob
- 棧幀的內存布局
- shell
- 時間處理
- time詳情
- time使用
- new和make的區別
- container
- list
- heap
- ring
- 測試
- 單元測試
- Mock依賴
- delve
- 命令
- TestMain
- path和filepath包
- log日志
- 反射
- 詳解
- plugin包
- 信號
- goto
- 協程
- 簡介
- 創建
- 協程退出
- runtime
- channel
- select
- 死鎖
- 互斥鎖
- 讀寫鎖
- 條件變量
- 嵌套
- 計算單個協程占用內存
- 執行規則
- 原子操作
- WaitGroup
- 定時器
- 對象池
- sync.once
- 網絡編程
- 分層模型
- socket
- tcp
- udp
- 服務端
- 客戶端
- 并發服務器
- Http
- 簡介
- http服務器
- http客戶端
- 爬蟲
- 平滑重啟
- context
- httptest
- 優雅中止
- web服務平滑重啟
- beego
- 安裝
- 路由器
- orm
- 單表增刪改查
- 多級表
- orm使用
- 高級查詢
- 關系查詢
- SQL查詢
- 元數據二次定義
- 控制器
- 參數解析
- 過濾器
- 數據輸出
- 表單數據驗證
- 錯誤處理
- 日志
- 模塊
- cache
- task
- 調試模塊
- config
- 部署
- 一些包
- gjson
- goredis
- collection
- sjson
- redigo
- aliyunoss
- 密碼
- 對稱加密
- 非對稱加密
- 單向散列函數
- 消息認證
- 數字簽名
- mysql優化
- 常見錯誤
- go run的錯誤
- 新手常見錯誤
- 中級錯誤
- 高級錯誤
- 常用工具
- 協程-泄露
- go env
- gometalinter代碼檢查
- go build
- go clean
- go test
- 包管理器
- go mod
- gopm
- go fmt
- pprof
- 提高編譯
- go get
- 代理
- 其他的知識
- go內存對齊
- 細節總結
- nginx路由匹配
- 一些博客
- redis為什么快
- cpu高速緩存
- 常用命令
- Go 永久阻塞的方法
- 常用技巧
- 密碼加密解密
- for 循環迭代變量
- 備注
- 垃圾回收
- 協程和纖程
- tar-gz
- 紅包算法
- 解決golang.org/x 下載失敗
- 逃逸分析
- docker
- 鏡像
- 容器
- 數據卷
- 網絡管理
- 網絡模式
- dockerfile
- docker-composer
- 微服務
- protoBuf
- GRPC
- tls
- consul
- micro
- crontab
- shell調用
- gorhill/cronexpr
- raft
- go操作etcd
- mongodb