Created
September 28, 2016 11:49
-
-
Save athurg/4a0f1866e9150be9d13c3ebf0240b4b3 to your computer and use it in GitHub Desktop.
生成OpenSSH兼容的密钥对代码
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import( | |
"fmt" | |
"io/ioutil" | |
"bytes" | |
"encoding/binary" | |
"crypto/rsa" | |
"crypto/rand" | |
"crypto/x509" | |
"encoding/base64" | |
"encoding/pem" | |
"math/big" | |
) | |
func main(){ | |
privateKey,err := rsa.GenerateKey(rand.Reader, 2048) | |
if err != nil { | |
fmt.Printf("Error %s", err) | |
return | |
} | |
derBytes := x509.MarshalPKCS1PrivateKey(privateKey) | |
pemBlock := pem.Block{Bytes:derBytes,Type:"RSA PRIVATE KEY"} | |
bytes := pem.EncodeToMemory(&pemBlock) | |
//fmt.Printf("%s\n\n", string(bytes)) | |
ioutil.WriteFile("id_rsa", bytes, 0600) | |
txt,err := EncodePublicKey(privateKey.PublicKey, "") | |
if err != nil { | |
fmt.Print("Invalid public key %s", err) | |
return | |
} | |
txt += "\n" | |
fmt.Printf("%s\n", txt) | |
ioutil.WriteFile("id_rsa.pub", []byte(txt), 0644) | |
} | |
func EncodePublicKey(key interface{}, comment string) (string, error) { | |
if rsaKey, ok := key.(rsa.PublicKey); ok { | |
key_type := "ssh-rsa" | |
modulus_bytes := rsaKey.N.Bytes() | |
intLen := binary.Size(int32(rsaKey.E)) | |
needLen := (big.NewInt(int64(rsaKey.E)).BitLen() + 7) / 8 | |
eBuf := make([]byte, intLen) | |
binary.BigEndian.PutUint32(eBuf, uint32(rsaKey.E)) | |
eBuf = eBuf[intLen-needLen:] | |
fmt.Println(eBuf) | |
var data = []interface{} { | |
uint32(len(key_type)), | |
[]byte(key_type), | |
uint32(needLen), //size of rsaKey.E | |
eBuf, | |
uint32(len(modulus_bytes)+1),//size of modulus_bytes | |
byte(0),//padding | |
modulus_bytes, | |
} | |
buf := new(bytes.Buffer) | |
for _, v := range data { | |
err := binary.Write(buf, binary.BigEndian, v) | |
if err != nil { return "", err } | |
} | |
if comment!="" { | |
comment = " " + comment | |
} | |
return fmt.Sprintf("%s %s"+comment, key_type, base64.StdEncoding.EncodeToString(buf.Bytes())), nil | |
} | |
return "", fmt.Errorf("Unknown key type: %T\n", key) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment