go-ipfs-config: Add Init Alternative allowing specification of ED25519 key
Will Scott committed
Apr 20, 2020 at 17:37 UTC
d02cdb3963957867b1e93edbb4ccf91a8290dec7
1 file changed
+38
-7
config/init.go
+38
-7
@@ -1,17 +1,23 @@
1
package config
2
3
import (
4
+ "crypto/rand"
5
"encoding/base64"
6
"fmt"
7
"io"
8
"time"
9
10
+ "github.com/ipfs/interface-go-ipfs-core/options"
11
ci "github.com/libp2p/go-libp2p-core/crypto"
12
peer "github.com/libp2p/go-libp2p-core/peer"
13
)
14
15
func Init(out io.Writer, nBitsForKeypair int) (*Config, error) {
14
- identity, err := identityConfig(out, nBitsForKeypair)
16
+ return InitWithOptions(out, []options.KeyGenerateOption{options.Key.Size(nBitsForKeypair)})
17
+}
18
+
19
+func InitWithOptions(out io.Writer, opts []options.KeyGenerateOption) (*Config, error) {
20
+ identity, err := identityConfig(out, opts)
21
if err != nil {
22
return nil, err
23
}
@@ -165,18 +171,43 @@ func flatfsSpec() map[string]interface{} {
171
}
172
173
// identityConfig initializes a new identity.
168
-func identityConfig(out io.Writer, nbits int) (Identity, error) {
174
+func identityConfig(out io.Writer, opts []options.KeyGenerateOption) (Identity, error) {
175
// TODO guard higher up
176
ident := Identity{}
171
- if nbits < ci.MinRsaKeyBits {
172
- return ident, ci.ErrRsaKeyTooSmall
173
- }
177
175
- fmt.Fprintf(out, "generating %v-bit RSA keypair...", nbits)
176
- sk, pk, err := ci.GenerateKeyPair(ci.RSA, nbits)
178
+ settings, err := options.KeyGenerateOptions(opts...)
179
if err != nil {
180
return ident, err
181
}
182
+
183
+ var sk ci.PrivKey
184
+ var pk ci.PubKey
185
+
186
+ fmt.Fprintf(out, "generating %s keypair...", settings.Algorithm)
187
+ switch settings.Algorithm {
188
+ case "rsa":
189
+ if settings.Size == -1 {
190
+ settings.Size = options.DefaultRSALen
191
+ }
192
+
193
+ priv, pub, err := ci.GenerateKeyPair(ci.RSA, settings.Size)
194
+ if err != nil {
195
+ return ident, err
196
+ }
197
+
198
+ sk = priv
199
+ pk = pub
200
+ case "ed25519":
201
+ priv, pub, err := ci.GenerateEd25519Key(rand.Reader)
202
+ if err != nil {
203
+ return ident, err
204
+ }
205
+
206
+ sk = priv
207
+ pk = pub
208
+ default:
209
+ return ident, fmt.Errorf("unrecognized key type: %s", settings.Algorithm)
210
+ }
211
fmt.Fprintf(out, "done\n")
212
213
// currently storing key unencrypted. in the future we need to encrypt it.