This is the 23rd day of my participation in the Gwen Challenge.More article challenges

Interface authentication scheme based on RSA encryption algorithm

Assuming that the interface caller is the client and the interface provider is the server, the scheme has the following rules:

  • The client needs to use the RSA algorithm (1024 bit private key) to generate public and private keys and send the public keys to the server.
  • The client uses the private key to sign the request content, and then sends the request content and signature to the server.
  • After receiving the request, the server uses the public key provided by the client to check the request content and signature to determine whether the request is from the client.

Generating public and private Keys

Generate 1024 bit private key
openssl genrsa -out private-key.pem 1024

Generate public key
openssl rsa -in private-key.pem -pubout -out public-key.pem
Copy the code

Code implementation

The signature of the

Use SHA1 + RSA to sign the request:

package utils

import (
	"crypto"
	"crypto/rand"
	"crypto/rsa"
	"crypto/sha1"
	"crypto/x509"
	"encoding/hex"
	"encoding/pem"
	"errors"
	"io/ioutil"
)

var (
	Privkey string
)

func Sign(s string) (string, error) {
	key, err := ioutil.ReadFile(Privkey)
	iferr ! =nil {
		return "", err
	}
	r, err := encryptSHA1WithRSA(key, []byte(s))
	iferr ! =nil {
		return "", err
	}
	return hex.EncodeToString(r), nil
}

func encryptSHA1WithRSA(key, data []byte) ([]byte, error) {
	block, _ := pem.Decode(key)
	if block == nil {
		return nil, errors.New("no PEM data is found")
	}

	private, err := x509.ParsePKCS1PrivateKey(block.Bytes)
	iferr ! =nil {
		return nil, err
	}
	hashed := SHA1(data)
	return rsa.SignPKCS1v15(rand.Reader, private, crypto.SHA1, hashed)
}

func SHA1(data []byte) []byte {
	h := sha1.New()
	h.Write(data)
	return h.Sum(nil)}Copy the code

attestation

package utils

import (
	"crypto"
	"crypto/rsa"
	"crypto/sha1"
	"crypto/x509"
	"encoding/hex"
	"encoding/pem"
	"io/ioutil"
)

var (
	Pubkey  string
)

func VerifySig(origin, sig string) error {
	b, err := ioutil.ReadFile(Pubkey)
	iferr ! =nil {
		return err
	}
	block, _ := pem.Decode(b)
	pub, err := x509.ParsePKIXPublicKey(block.Bytes)
	iferr ! =nil {
		return err
	}
	hashed := SHA1([]byte(origin))
	sigBytes, err := hex.DecodeString(sig)
	iferr ! =nil {
		return err
	}
	return rsa.VerifyPKCS1v15(pub.(*rsa.PublicKey), crypto.SHA1, hashed, []byte(sigBytes))
}

func SHA1(data []byte) []byte {
	h := sha1.New()
	h.Write(data)
	return h.Sum(nil)}Copy the code