code.vegaprotocol.io/vega@v0.79.0/wallet/service/v1/rsa.go (about) 1 // Copyright (C) 2023 Gobalsky Labs Limited 2 // 3 // This program is free software: you can redistribute it and/or modify 4 // it under the terms of the GNU Affero General Public License as 5 // published by the Free Software Foundation, either version 3 of the 6 // License, or (at your option) any later version. 7 // 8 // This program is distributed in the hope that it will be useful, 9 // but WITHOUT ANY WARRANTY; without even the implied warranty of 10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 // GNU Affero General Public License for more details. 12 // 13 // You should have received a copy of the GNU Affero General Public License 14 // along with this program. If not, see <http://www.gnu.org/licenses/>. 15 16 package v1 17 18 import ( 19 "bytes" 20 "crypto/rand" 21 "crypto/rsa" 22 "crypto/x509" 23 "encoding/pem" 24 "fmt" 25 ) 26 27 type RSAKeys struct { 28 Pub []byte 29 Priv []byte 30 } 31 32 func GenerateRSAKeys() (*RSAKeys, error) { 33 bitSize := 4096 34 35 key, err := rsa.GenerateKey(rand.Reader, bitSize) 36 if err != nil { 37 return nil, fmt.Errorf("couldn't generate RSA keys: %w", err) 38 } 39 40 privateKey, err := toPrivatePKCS1Key(key) 41 if err != nil { 42 return nil, fmt.Errorf("couldn't extract private RSA key: %w", err) 43 } 44 45 publicKey, err := toPublicPKCS1Key(key) 46 if err != nil { 47 return nil, fmt.Errorf("couldn't extract public RSA key: %w", err) 48 } 49 50 return &RSAKeys{ 51 Pub: publicKey, 52 Priv: privateKey, 53 }, nil 54 } 55 56 func toPrivatePKCS1Key(key *rsa.PrivateKey) ([]byte, error) { 57 privateKey := &pem.Block{ 58 Type: "RSA PRIVATE KEY", 59 Bytes: x509.MarshalPKCS1PrivateKey(key), 60 } 61 privateKeyBuffer := bytes.NewBuffer([]byte{}) 62 err := pem.Encode(privateKeyBuffer, privateKey) 63 if err != nil { 64 return nil, fmt.Errorf("couldn't encode private RSA key: %w", err) 65 } 66 return privateKeyBuffer.Bytes(), nil 67 } 68 69 func toPublicPKCS1Key(key *rsa.PrivateKey) ([]byte, error) { 70 pubBytes, err := x509.MarshalPKIXPublicKey(&key.PublicKey) 71 if err != nil { 72 return nil, fmt.Errorf("couldn't marshal public RSA key: %w", err) 73 } 74 publicKey := &pem.Block{ 75 Type: "PUBLIC KEY", 76 Bytes: pubBytes, 77 } 78 publicKeyBuffer := bytes.NewBuffer([]byte{}) 79 err = pem.Encode(publicKeyBuffer, publicKey) 80 if err != nil { 81 return nil, fmt.Errorf("couldn't encode public RSA key: %w", err) 82 } 83 return publicKeyBuffer.Bytes(), nil 84 }