Created
December 27, 2017 14:33
-
-
Save kingwrcy/79a4c4c5d97b8ad2997f1525eee77550 to your computer and use it in GitHub Desktop.
rsa test file
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 ( | |
"crypto/rsa" | |
"crypto/rand" | |
"fmt" | |
"encoding/pem" | |
"crypto/x509" | |
"encoding/asn1" | |
"crypto" | |
"encoding/base64" | |
) | |
func MarshalPKCS8PrivateKey(key *rsa.PrivateKey) []byte { | |
info := struct { | |
Version int | |
PrivateKeyAlgorithm []asn1.ObjectIdentifier | |
PrivateKey []byte | |
}{} | |
info.Version = 0 | |
info.PrivateKeyAlgorithm = make([]asn1.ObjectIdentifier, 1) | |
info.PrivateKeyAlgorithm[0] = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 1} | |
info.PrivateKey = x509.MarshalPKCS1PrivateKey(key) | |
k, err := asn1.Marshal(info) | |
if err != nil { | |
fmt.Println("Error",err) | |
} | |
return k | |
} | |
func main() { | |
generateKey, err := rsa.GenerateKey(rand.Reader, 1024) | |
if err != nil { | |
fmt.Println("GenerateKey Error",err) | |
} | |
derStream := x509.MarshalPKCS1PrivateKey(generateKey) | |
block := &pem.Block{ | |
Type: "RSA PRIVATE KEY", | |
Bytes: derStream, | |
} | |
priKey := pem.EncodeToMemory(block) | |
fmt.Printf("Private Key:\n%s\n",string(priKey)) | |
marshal, err := asn1.Marshal(generateKey.PublicKey) | |
if err != nil { | |
fmt.Println("Marshal Error",err) | |
} | |
var pemkey = &pem.Block{ | |
Type: "RSA PUBLIC KEY", | |
Bytes: marshal, | |
} | |
pubKey := pem.EncodeToMemory(pemkey) | |
fmt.Printf("Public Key:\n%s\n",string(pubKey)) | |
data := "hahhaha" | |
p, _ := pem.Decode(priKey) | |
key, _ := x509.ParsePKCS1PrivateKey(p.Bytes) | |
hash := crypto.SHA1.New() | |
hash.Write([]byte(data)) | |
hh := hash.Sum(nil) | |
r, _ := rsa.SignPKCS1v15(rand.Reader, key, crypto.SHA1, hh) | |
fmt.Printf("pkcs8 Public Key:\n%s\n",base64.StdEncoding.EncodeToString(MarshalPKCS8PrivateKey(key))) | |
fmt.Println("data:",data) | |
fmt.Printf("sign:%s\n",base64.StdEncoding.EncodeToString(r)) | |
//publicKInterface, err := x509.MarshalPKIXPublicKey(aa) | |
if err != nil { | |
fmt.Println("err",err) | |
} | |
err = rsa.VerifyPKCS1v15(&generateKey.PublicKey, crypto.SHA1, hh, r) | |
if err != nil { | |
fmt.Println("Verify FAIL") | |
}else{ | |
fmt.Println("Verify PASS") | |
} | |
o, _ := rsa.EncryptPKCS1v15(rand.Reader, &generateKey.PublicKey, []byte(data)) | |
fmt.Println("encrypt:",base64.StdEncoding.EncodeToString(o)) | |
r, _ = rsa.DecryptPKCS1v15(rand.Reader, key, o) | |
fmt.Println("dencrypt:",string(r)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment