Created
February 14, 2025 19:16
-
-
Save huangsam/154441669b85af227f11e7fd1437d897 to your computer and use it in GitHub Desktop.
SSH verification in Go
This file contains 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 ( | |
"bytes" | |
"os" | |
"github.com/rs/zerolog/log" | |
"golang.org/x/crypto/ssh" | |
) | |
var ( | |
SSHBasePath = os.Getenv("HOME") + "/.ssh" | |
PublicKeyPath = SSHBasePath + "/id_ed25519.pub" | |
PrivateKeyPath = SSHBasePath + "/id_ed25519" | |
) | |
// readAndParsePublicKey reads and parses the public key. | |
func readAndParsePublicKey() ssh.PublicKey { | |
keyBytes, err := os.ReadFile(PublicKeyPath) | |
if err != nil { | |
log.Fatal().Err(err).Msg("Failed to read public key file") | |
} | |
pubKey, _, _, _, err := ssh.ParseAuthorizedKey(keyBytes) | |
if err != nil { | |
log.Fatal().Err(err).Msg("Failed to parse public key") | |
} | |
return pubKey | |
} | |
// readAndParsePrivateKey reads and parses the private key. | |
func readAndParsePrivateKey() ssh.Signer { | |
keyBytes, err := os.ReadFile(PrivateKeyPath) | |
if err != nil { | |
log.Fatal().Err(err).Msg("Failed to read private key file") | |
} | |
signer, err := ssh.ParsePrivateKey(keyBytes) | |
if err != nil { | |
log.Fatal().Err(err).Msg("Failed to parse private key") | |
} | |
return signer | |
} | |
func main() { | |
var pubKey ssh.PublicKey = readAndParsePublicKey() | |
var privKey ssh.Signer = readAndParsePrivateKey() | |
if pubKey == nil || privKey == nil { | |
log.Fatal().Msg("Failed to read or parse keys") | |
} | |
// Verify that the private key matches the public key | |
if !bytes.Equal(pubKey.Marshal(), privKey.PublicKey().Marshal()) { | |
log.Fatal().Msg("Public and private keys do not match") | |
} | |
log.Info().Msg("Public and private keys match") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment