pkcs8.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  1. /*
  2. Copyright Suzhou Tongji Fintech Research Institute 2017 All Rights Reserved.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package sm2
  14. import (
  15. "crypto/aes"
  16. "crypto/cipher"
  17. "crypto/elliptic"
  18. "crypto/hmac"
  19. "crypto/md5"
  20. "crypto/rand"
  21. "crypto/sha1"
  22. "crypto/sha256"
  23. "crypto/sha512"
  24. "crypto/x509/pkix"
  25. "encoding/asn1"
  26. "encoding/pem"
  27. "errors"
  28. "hash"
  29. "io/ioutil"
  30. "math/big"
  31. "os"
  32. "reflect"
  33. )
  34. /*
  35. * reference to RFC5959 and RFC2898
  36. */
  37. var (
  38. oidPBES1 = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 5, 3} // pbeWithMD5AndDES-CBC(PBES1)
  39. oidPBES2 = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 5, 13} // id-PBES2(PBES2)
  40. oidPBKDF2 = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 5, 12} // id-PBKDF2
  41. oidKEYMD5 = asn1.ObjectIdentifier{1, 2, 840, 113549, 2, 5}
  42. oidKEYSHA1 = asn1.ObjectIdentifier{1, 2, 840, 113549, 2, 7}
  43. oidKEYSHA256 = asn1.ObjectIdentifier{1, 2, 840, 113549, 2, 9}
  44. oidKEYSHA512 = asn1.ObjectIdentifier{1, 2, 840, 113549, 2, 11}
  45. oidAES128CBC = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 1, 2}
  46. oidAES256CBC = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 1, 42}
  47. oidSM2 = asn1.ObjectIdentifier{1, 2, 840, 10045, 2, 1}
  48. )
  49. // reference to https://www.rfc-editor.org/rfc/rfc5958.txt
  50. type PrivateKeyInfo struct {
  51. Version int // v1 or v2
  52. PrivateKeyAlgorithm []asn1.ObjectIdentifier
  53. PrivateKey []byte
  54. }
  55. // reference to https://www.rfc-editor.org/rfc/rfc5958.txt
  56. type EncryptedPrivateKeyInfo struct {
  57. EncryptionAlgorithm Pbes2Algorithms
  58. EncryptedData []byte
  59. }
  60. // reference to https://www.ietf.org/rfc/rfc2898.txt
  61. type Pbes2Algorithms struct {
  62. IdPBES2 asn1.ObjectIdentifier
  63. Pbes2Params Pbes2Params
  64. }
  65. // reference to https://www.ietf.org/rfc/rfc2898.txt
  66. type Pbes2Params struct {
  67. KeyDerivationFunc Pbes2KDfs // PBES2-KDFs
  68. EncryptionScheme Pbes2Encs // PBES2-Encs
  69. }
  70. // reference to https://www.ietf.org/rfc/rfc2898.txt
  71. type Pbes2KDfs struct {
  72. IdPBKDF2 asn1.ObjectIdentifier
  73. Pkdf2Params Pkdf2Params
  74. }
  75. type Pbes2Encs struct {
  76. EncryAlgo asn1.ObjectIdentifier
  77. IV []byte
  78. }
  79. // reference to https://www.ietf.org/rfc/rfc2898.txt
  80. type Pkdf2Params struct {
  81. Salt []byte
  82. IterationCount int
  83. Prf pkix.AlgorithmIdentifier
  84. }
  85. type sm2PrivateKey struct {
  86. Version int
  87. PrivateKey []byte
  88. NamedCurveOID asn1.ObjectIdentifier `asn1:"optional,explicit,tag:0"`
  89. PublicKey asn1.BitString `asn1:"optional,explicit,tag:1"`
  90. }
  91. type pkcs8 struct {
  92. Version int
  93. Algo pkix.AlgorithmIdentifier
  94. PrivateKey []byte
  95. }
  96. // copy from crypto/pbkdf2.go
  97. func pbkdf(password, salt []byte, iter, keyLen int, h func() hash.Hash) []byte {
  98. prf := hmac.New(h, password)
  99. hashLen := prf.Size()
  100. numBlocks := (keyLen + hashLen - 1) / hashLen
  101. var buf [4]byte
  102. dk := make([]byte, 0, numBlocks*hashLen)
  103. U := make([]byte, hashLen)
  104. for block := 1; block <= numBlocks; block++ {
  105. // N.B.: || means concatenation, ^ means XOR
  106. // for each block T_i = U_1 ^ U_2 ^ ... ^ U_iter
  107. // U_1 = PRF(password, salt || uint(i))
  108. prf.Reset()
  109. prf.Write(salt)
  110. buf[0] = byte(block >> 24)
  111. buf[1] = byte(block >> 16)
  112. buf[2] = byte(block >> 8)
  113. buf[3] = byte(block)
  114. prf.Write(buf[:4])
  115. dk = prf.Sum(dk)
  116. T := dk[len(dk)-hashLen:]
  117. copy(U, T)
  118. // U_n = PRF(password, U_(n-1))
  119. for n := 2; n <= iter; n++ {
  120. prf.Reset()
  121. prf.Write(U)
  122. U = U[:0]
  123. U = prf.Sum(U)
  124. for x := range U {
  125. T[x] ^= U[x]
  126. }
  127. }
  128. }
  129. return dk[:keyLen]
  130. }
  131. func ParseSm2PublicKey(der []byte) (*PublicKey, error) {
  132. var pubkey pkixPublicKey
  133. if _, err := asn1.Unmarshal(der, &pubkey); err != nil {
  134. return nil, err
  135. }
  136. if !reflect.DeepEqual(pubkey.Algo.Algorithm, oidSM2) {
  137. return nil, errors.New("x509: not sm2 elliptic curve")
  138. }
  139. curve := P256Sm2()
  140. x, y := elliptic.Unmarshal(curve, pubkey.BitString.Bytes)
  141. pub := PublicKey{
  142. Curve: curve,
  143. X: x,
  144. Y: y,
  145. }
  146. return &pub, nil
  147. }
  148. func MarshalSm2PublicKey(key *PublicKey) ([]byte, error) {
  149. var r pkixPublicKey
  150. var algo pkix.AlgorithmIdentifier
  151. algo.Algorithm = oidSM2
  152. algo.Parameters.Class = 0
  153. algo.Parameters.Tag = 6
  154. algo.Parameters.IsCompound = false
  155. algo.Parameters.FullBytes = []byte{6, 8, 42, 129, 28, 207, 85, 1, 130, 45} // asn1.Marshal(asn1.ObjectIdentifier{1, 2, 156, 10197, 1, 301})
  156. r.Algo = algo
  157. r.BitString = asn1.BitString{Bytes: elliptic.Marshal(key.Curve, key.X, key.Y)}
  158. return asn1.Marshal(r)
  159. }
  160. func ParseSm2PrivateKey(der []byte) (*PrivateKey, error) {
  161. var privKey sm2PrivateKey
  162. if _, err := asn1.Unmarshal(der, &privKey); err != nil {
  163. return nil, errors.New("x509: failed to parse SM2 private key: " + err.Error())
  164. }
  165. curve := P256Sm2()
  166. k := new(big.Int).SetBytes(privKey.PrivateKey)
  167. curveOrder := curve.Params().N
  168. if k.Cmp(curveOrder) >= 0 {
  169. return nil, errors.New("x509: invalid elliptic curve private key value")
  170. }
  171. priv := new(PrivateKey)
  172. priv.Curve = curve
  173. priv.D = k
  174. privateKey := make([]byte, (curveOrder.BitLen()+7)/8)
  175. for len(privKey.PrivateKey) > len(privateKey) {
  176. if privKey.PrivateKey[0] != 0 {
  177. return nil, errors.New("x509: invalid private key length")
  178. }
  179. privKey.PrivateKey = privKey.PrivateKey[1:]
  180. }
  181. copy(privateKey[len(privateKey)-len(privKey.PrivateKey):], privKey.PrivateKey)
  182. priv.X, priv.Y = curve.ScalarBaseMult(privateKey)
  183. return priv, nil
  184. }
  185. func ParsePKCS8UnecryptedPrivateKey(der []byte) (*PrivateKey, error) {
  186. var privKey pkcs8
  187. if _, err := asn1.Unmarshal(der, &privKey); err != nil {
  188. return nil, err
  189. }
  190. if !reflect.DeepEqual(privKey.Algo.Algorithm, oidSM2) {
  191. return nil, errors.New("x509: not sm2 elliptic curve")
  192. }
  193. return ParseSm2PrivateKey(privKey.PrivateKey)
  194. }
  195. func ParsePKCS8EcryptedPrivateKey(der, pwd []byte) (*PrivateKey, error) {
  196. var keyInfo EncryptedPrivateKeyInfo
  197. _, err := asn1.Unmarshal(der, &keyInfo)
  198. if err != nil {
  199. return nil, errors.New("x509: unknown format")
  200. }
  201. if !reflect.DeepEqual(keyInfo.EncryptionAlgorithm.IdPBES2, oidPBES2) {
  202. return nil, errors.New("x509: only support PBES2")
  203. }
  204. encryptionScheme := keyInfo.EncryptionAlgorithm.Pbes2Params.EncryptionScheme
  205. keyDerivationFunc := keyInfo.EncryptionAlgorithm.Pbes2Params.KeyDerivationFunc
  206. if !reflect.DeepEqual(keyDerivationFunc.IdPBKDF2, oidPBKDF2) {
  207. return nil, errors.New("x509: only support PBKDF2")
  208. }
  209. pkdf2Params := keyDerivationFunc.Pkdf2Params
  210. if !reflect.DeepEqual(encryptionScheme.EncryAlgo, oidAES128CBC) &&
  211. !reflect.DeepEqual(encryptionScheme.EncryAlgo, oidAES256CBC) {
  212. return nil, errors.New("x509: unknow encryption algorithm")
  213. }
  214. iv := encryptionScheme.IV
  215. salt := pkdf2Params.Salt
  216. iter := pkdf2Params.IterationCount
  217. encryptedKey := keyInfo.EncryptedData
  218. var key []byte
  219. switch {
  220. case pkdf2Params.Prf.Algorithm.Equal(oidKEYMD5):
  221. key = pbkdf(pwd, salt, iter, 32, md5.New)
  222. break
  223. case pkdf2Params.Prf.Algorithm.Equal(oidKEYSHA1):
  224. key = pbkdf(pwd, salt, iter, 32, sha1.New)
  225. break
  226. case pkdf2Params.Prf.Algorithm.Equal(oidKEYSHA256):
  227. key = pbkdf(pwd, salt, iter, 32, sha256.New)
  228. break
  229. case pkdf2Params.Prf.Algorithm.Equal(oidKEYSHA512):
  230. key = pbkdf(pwd, salt, iter, 32, sha512.New)
  231. break
  232. default:
  233. return nil, errors.New("x509: unknown hash algorithm")
  234. }
  235. block, err := aes.NewCipher(key)
  236. if err != nil {
  237. return nil, err
  238. }
  239. mode := cipher.NewCBCDecrypter(block, iv)
  240. mode.CryptBlocks(encryptedKey, encryptedKey)
  241. rKey, err := ParsePKCS8UnecryptedPrivateKey(encryptedKey)
  242. if err != nil {
  243. return nil, errors.New("pkcs8: incorrect password")
  244. }
  245. return rKey, nil
  246. }
  247. func ParsePKCS8PrivateKey(der, pwd []byte) (*PrivateKey, error) {
  248. if pwd == nil {
  249. return ParsePKCS8UnecryptedPrivateKey(der)
  250. }
  251. return ParsePKCS8EcryptedPrivateKey(der, pwd)
  252. }
  253. func MarshalSm2UnecryptedPrivateKey(key *PrivateKey) ([]byte, error) {
  254. var r pkcs8
  255. var priv sm2PrivateKey
  256. var algo pkix.AlgorithmIdentifier
  257. algo.Algorithm = oidSM2
  258. algo.Parameters.Class = 0
  259. algo.Parameters.Tag = 6
  260. algo.Parameters.IsCompound = false
  261. algo.Parameters.FullBytes = []byte{6, 8, 42, 129, 28, 207, 85, 1, 130, 45} // asn1.Marshal(asn1.ObjectIdentifier{1, 2, 156, 10197, 1, 301})
  262. priv.Version = 1
  263. priv.NamedCurveOID = oidNamedCurveP256SM2
  264. priv.PublicKey = asn1.BitString{Bytes: elliptic.Marshal(key.Curve, key.X, key.Y)}
  265. priv.PrivateKey = key.D.Bytes()
  266. r.Version = 0
  267. r.Algo = algo
  268. r.PrivateKey, _ = asn1.Marshal(priv)
  269. return asn1.Marshal(r)
  270. }
  271. func MarshalSm2EcryptedPrivateKey(PrivKey *PrivateKey, pwd []byte) ([]byte, error) {
  272. der, err := MarshalSm2UnecryptedPrivateKey(PrivKey)
  273. if err != nil {
  274. return nil, err
  275. }
  276. iter := 2048
  277. salt := make([]byte, 8)
  278. iv := make([]byte, 16)
  279. rand.Reader.Read(salt)
  280. rand.Reader.Read(iv)
  281. key := pbkdf(pwd, salt, iter, 32, sha1.New) // 默认是SHA1
  282. padding := aes.BlockSize - len(der)%aes.BlockSize
  283. if padding > 0 {
  284. n := len(der)
  285. der = append(der, make([]byte, padding)...)
  286. for i := 0; i < padding; i++ {
  287. der[n+i] = byte(padding)
  288. }
  289. }
  290. encryptedKey := make([]byte, len(der))
  291. block, err := aes.NewCipher(key)
  292. if err != nil {
  293. return nil, err
  294. }
  295. mode := cipher.NewCBCEncrypter(block, iv)
  296. mode.CryptBlocks(encryptedKey, der)
  297. var algorithmIdentifier pkix.AlgorithmIdentifier
  298. algorithmIdentifier.Algorithm = oidKEYSHA1
  299. algorithmIdentifier.Parameters.Tag = 5
  300. algorithmIdentifier.Parameters.IsCompound = false
  301. algorithmIdentifier.Parameters.FullBytes = []byte{5, 0}
  302. keyDerivationFunc := Pbes2KDfs{
  303. oidPBKDF2,
  304. Pkdf2Params{
  305. salt,
  306. iter,
  307. algorithmIdentifier,
  308. },
  309. }
  310. encryptionScheme := Pbes2Encs{
  311. oidAES256CBC,
  312. iv,
  313. }
  314. pbes2Algorithms := Pbes2Algorithms{
  315. oidPBES2,
  316. Pbes2Params{
  317. keyDerivationFunc,
  318. encryptionScheme,
  319. },
  320. }
  321. encryptedPkey := EncryptedPrivateKeyInfo{
  322. pbes2Algorithms,
  323. encryptedKey,
  324. }
  325. return asn1.Marshal(encryptedPkey)
  326. }
  327. func MarshalSm2PrivateKey(key *PrivateKey, pwd []byte) ([]byte, error) {
  328. if pwd == nil {
  329. return MarshalSm2UnecryptedPrivateKey(key)
  330. }
  331. return MarshalSm2EcryptedPrivateKey(key, pwd)
  332. }
  333. func ReadPrivateKeyFromMem(data []byte, pwd []byte) (*PrivateKey, error) {
  334. var block *pem.Block
  335. block, _ = pem.Decode(data)
  336. if block == nil {
  337. return nil, errors.New("failed to decode private key")
  338. }
  339. priv, err := ParsePKCS8PrivateKey(block.Bytes, pwd)
  340. return priv, err
  341. }
  342. func ReadPrivateKeyFromPem(FileName string, pwd []byte) (*PrivateKey, error) {
  343. data, err := ioutil.ReadFile(FileName)
  344. if err != nil {
  345. return nil, err
  346. }
  347. return ReadPrivateKeyFromMem(data, pwd)
  348. }
  349. func WritePrivateKeytoMem(key *PrivateKey, pwd []byte) ([]byte, error) {
  350. var block *pem.Block
  351. der, err := MarshalSm2PrivateKey(key, pwd)
  352. if err != nil {
  353. return nil, err
  354. }
  355. if pwd != nil {
  356. block = &pem.Block{
  357. Type: "ENCRYPTED PRIVATE KEY",
  358. Bytes: der,
  359. }
  360. } else {
  361. block = &pem.Block{
  362. Type: "PRIVATE KEY",
  363. Bytes: der,
  364. }
  365. }
  366. return pem.EncodeToMemory(block), nil
  367. }
  368. func WritePrivateKeytoPem(FileName string, key *PrivateKey, pwd []byte) (bool, error) {
  369. var block *pem.Block
  370. der, err := MarshalSm2PrivateKey(key, pwd)
  371. if err != nil {
  372. return false, err
  373. }
  374. if pwd != nil {
  375. block = &pem.Block{
  376. Type: "ENCRYPTED PRIVATE KEY",
  377. Bytes: der,
  378. }
  379. } else {
  380. block = &pem.Block{
  381. Type: "PRIVATE KEY",
  382. Bytes: der,
  383. }
  384. }
  385. file, err := os.Create(FileName)
  386. if err != nil {
  387. return false, err
  388. }
  389. defer file.Close()
  390. err = pem.Encode(file, block)
  391. if err != nil {
  392. return false, err
  393. }
  394. return true, nil
  395. }
  396. func ReadPublicKeyFromMem(data []byte, _ []byte) (*PublicKey, error) {
  397. block, _ := pem.Decode(data)
  398. if block == nil || block.Type != "PUBLIC KEY" {
  399. return nil, errors.New("failed to decode public key")
  400. }
  401. pub, err := ParseSm2PublicKey(block.Bytes)
  402. return pub, err
  403. }
  404. func ReadPublicKeyFromPem(FileName string, pwd []byte) (*PublicKey, error) {
  405. data, err := ioutil.ReadFile(FileName)
  406. if err != nil {
  407. return nil, err
  408. }
  409. return ReadPublicKeyFromMem(data, pwd)
  410. }
  411. func WritePublicKeytoMem(key *PublicKey, _ []byte) ([]byte, error) {
  412. der, err := MarshalSm2PublicKey(key)
  413. if err != nil {
  414. return nil, err
  415. }
  416. block := &pem.Block{
  417. Type: "PUBLIC KEY",
  418. Bytes: der,
  419. }
  420. return pem.EncodeToMemory(block), nil
  421. }
  422. func WritePublicKeytoPem(FileName string, key *PublicKey, _ []byte) (bool, error) {
  423. der, err := MarshalSm2PublicKey(key)
  424. if err != nil {
  425. return false, err
  426. }
  427. block := &pem.Block{
  428. Type: "PUBLIC KEY",
  429. Bytes: der,
  430. }
  431. file, err := os.Create(FileName)
  432. defer file.Close()
  433. if err != nil {
  434. return false, err
  435. }
  436. err = pem.Encode(file, block)
  437. if err != nil {
  438. return false, err
  439. }
  440. return true, nil
  441. }