예제 #1
2
파일: crypto.go 프로젝트: nicnys-8/mdc
func importKeyFromString(str string) (prv *rsa.PrivateKey, pub *rsa.PublicKey, err error) {
	cert := []byte(str)
	for {
		var blk *pem.Block
		blk, cert = pem.Decode(cert)
		if blk == nil {
			break
		}
		switch blk.Type {
		case "RSA PRIVATE KEY":
			prv, err = x509.ParsePKCS1PrivateKey(blk.Bytes)
			return
		case "RSA PUBLIC KEY":
			var in interface{}
			in, err = x509.ParsePKIXPublicKey(blk.Bytes)
			if err != nil {
				return
			}
			pub = in.(*rsa.PublicKey)
			return
		}
		if cert == nil || len(cert) == 0 {
			break
		}
	}
	return
}
예제 #2
2
파일: rsa_utils.go 프로젝트: fujitsu-cf/cli
// ParseRSAPublicKeyFromPEM parses PEM encoded PKCS1 or PKCS8 public key.
func ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error) {
	var err error

	// Parse PEM block
	var block *pem.Block
	if block, _ = pem.Decode(key); block == nil {
		return nil, ErrKeyMustBePEMEncoded
	}

	// Parse the key
	var parsedKey interface{}
	if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil {
		if cert, err := x509.ParseCertificate(block.Bytes); err == nil {
			parsedKey = cert.PublicKey
		} else {
			return nil, err
		}
	}

	var pkey *rsa.PublicKey
	var ok bool
	if pkey, ok = parsedKey.(*rsa.PublicKey); !ok {
		return nil, ErrNotRSAPublicKey
	}

	return pkey, nil
}
예제 #3
2
func fetchPubkey() (*rsa.PublicKey, error) {
	resp, err := http.Get("https://s3o.ft.com/publickey")
	if err != nil || resp.StatusCode != http.StatusOK {
		return nil, errors.New("failed to read s3o public key")
	}
	defer func() {
		_, _ = io.Copy(ioutil.Discard, resp.Body)
		_ = resp.Body.Close()
	}()
	var buf bytes.Buffer
	if _, err := io.Copy(&buf, resp.Body); err != nil {
		return nil, errors.New("failed to read s3o public key")
	}
	dec := make([]byte, 8192) // should be enough for a while.
	i, err := base64.StdEncoding.Decode(dec, buf.Bytes())
	if err != nil {
		return nil, errors.New("failed to base64 decode s3o public key")
	}

	pub, err := x509.ParsePKIXPublicKey(dec[0:i])
	if err != nil {
		return nil, errors.New("failed to parse s3o public key")
	}
	return pub.(*rsa.PublicKey), nil
}
예제 #4
1
func init() {
	var err error
	var pemBytes []byte
	var pub crypto.PublicKey
	var p *pem.Block

	if client, err = NewClient(certFile, keyFile, caFile, ioutil.Discard); err != nil {
		log.Fatal(err)
	}

	if pemBytes, err = ioutil.ReadFile(rsaPubKey); err != nil {
		log.Fatal(err)
	}
	p, _ = pem.Decode(pemBytes)
	if pub, err = x509.ParsePKIXPublicKey(p.Bytes); err != nil {
		log.Fatal(err)
	}
	if rsaKey, err = client.RegisterPublicKey(server, pub); err != nil {
		log.Fatal(err)
	}

	if pemBytes, err = ioutil.ReadFile(ecdsaPubKey); err != nil {
		log.Fatal(err)
	}
	p, _ = pem.Decode(pemBytes)
	if pub, err = x509.ParsePKIXPublicKey(p.Bytes); err != nil {
		log.Fatal(err)
	}
	if ecdsaKey, err = client.RegisterPublicKey(server, pub); err != nil {
		log.Fatal(err)
	}
}
예제 #5
0
// NewLog returns an initialized Log struct
func NewLog(uri, b64PK string) (*Log, error) {
	url, err := url.Parse(uri)
	if err != nil {
		return nil, err
	}
	url.Path = strings.TrimSuffix(url.Path, "/")
	client := ctClient.New(url.String(), nil)

	pkBytes, err := base64.StdEncoding.DecodeString(b64PK)
	if err != nil {
		return nil, fmt.Errorf("Failed to decode base64 log public key")
	}
	pk, err := x509.ParsePKIXPublicKey(pkBytes)
	if err != nil {
		return nil, fmt.Errorf("Failed to parse log public key")
	}

	verifier, err := ct.NewSignatureVerifier(pk)
	if err != nil {
		return nil, err
	}

	// Replace slashes with dots for statsd logging
	sanitizedPath := strings.TrimPrefix(url.Path, "/")
	sanitizedPath = strings.Replace(sanitizedPath, "/", ".", -1)

	return &Log{
		logID:    b64PK,
		uri:      uri,
		statName: fmt.Sprintf("%s.%s", url.Host, sanitizedPath),
		client:   client,
		verifier: verifier,
	}, nil
}
예제 #6
0
파일: rs256.go 프로젝트: bakanis/jwt
func (m *SigningMethodRS256) Verify(signingString, signature string, key []byte) (err error) {
	// Key
	var sig []byte
	if sig, err = DecodeSegment(signature); err == nil {
		var block *pem.Block
		if block, _ = pem.Decode(key); block != nil {
			var parsedKey interface{}
			if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil {
				parsedKey, err = x509.ParseCertificate(block.Bytes)
			}
			if err == nil {
				if rsaKey, ok := parsedKey.(*rsa.PublicKey); ok {
					hasher := sha256.New()
					hasher.Write([]byte(signingString))

					err = rsa.VerifyPKCS1v15(rsaKey, crypto.SHA256, hasher.Sum(nil), sig)
				} else if cert, ok := parsedKey.(*x509.Certificate); ok {
					err = cert.CheckSignature(x509.SHA256WithRSA, []byte(signingString), sig)
				} else {
					err = errors.New("Key is not a valid RSA public key")
				}
			}
		} else {
			err = errors.New("Could not parse key data")
		}
	}
	return
}
func getPublicKey() *rsa.PublicKey {
	publicKeyFile, err := os.Open(settings.Get().PublicKeyPath)
	if err != nil {
		panic(err)
	}

	pemfileinfo, _ := publicKeyFile.Stat()
	var size int64 = pemfileinfo.Size()
	pembytes := make([]byte, size)

	buffer := bufio.NewReader(publicKeyFile)
	_, err = buffer.Read(pembytes)

	data, _ := pem.Decode([]byte(pembytes))

	publicKeyFile.Close()

	publicKeyImported, err := x509.ParsePKIXPublicKey(data.Bytes)

	if err != nil {
		panic(err)
	}

	rsaPub, ok := publicKeyImported.(*rsa.PublicKey)

	if !ok {
		panic(err)
	}

	return rsaPub
}
예제 #8
0
// ImportPEM imports an RSA key from a file. It works with both public and
// private keys.
func ImportPEM(filename string) (prv *rsa.PrivateKey, pub *rsa.PublicKey, err error) {
	cert, err := ioutil.ReadFile(filename)
	if err != nil {
		return
	}

	for {
		var blk *pem.Block
		blk, cert = pem.Decode(cert)
		if blk == nil {
			break
		}
		switch blk.Type {
		case "RSA PRIVATE KEY":
			prv, err = x509.ParsePKCS1PrivateKey(blk.Bytes)
			return
		case "RSA PUBLIC KEY":
			var in interface{}
			in, err = x509.ParsePKIXPublicKey(blk.Bytes)
			if err != nil {
				return
			}
			pub = in.(*rsa.PublicKey)
			return
		}
		if cert == nil || len(cert) == 0 {
			break
		}
	}
	return
}
예제 #9
0
func ParsePublicKey(path string) *rsa.PublicKey {
	in, err := ioutil.ReadFile(path)
	if err != nil {
		log.Fatalf("%v", err)
	}

	if p, _ := pem.Decode(in); p != nil {
		if p.Type != "PUBLIC KEY" && p.Type != "RSA PUBLIC KEY" {
			log.Fatalf("invalid public key (type is %s)",
				p.Type)
		}
		in = p.Bytes
	}
	pub, err := x509.ParsePKIXPublicKey(in)
	if err != nil {
		log.Fatalf("failed to parse certificate: %v", err)
	}

	switch pub := pub.(type) {
	case *rsa.PublicKey:
		return pub
	default:
		log.Fatalf("only RSA public keys are supported")
		return nil
	}
}
예제 #10
0
func getRSAPubKey(key data.PublicKey) (crypto.PublicKey, error) {
	algorithm := key.Algorithm()
	var pubKey crypto.PublicKey

	switch algorithm {
	case data.RSAx509Key:
		pemCert, _ := pem.Decode([]byte(key.Public()))
		if pemCert == nil {
			logrus.Debugf("failed to decode PEM-encoded x509 certificate")
			return nil, ErrInvalid
		}
		cert, err := x509.ParseCertificate(pemCert.Bytes)
		if err != nil {
			logrus.Debugf("failed to parse x509 certificate: %s\n", err)
			return nil, ErrInvalid
		}
		pubKey = cert.PublicKey
	case data.RSAKey:
		var err error
		pubKey, err = x509.ParsePKIXPublicKey(key.Public())
		if err != nil {
			logrus.Debugf("failed to parse public key: %s\n", err)
			return nil, ErrInvalid
		}
	default:
		// only accept RSA keys
		logrus.Debugf("invalid key type for RSAPSS verifier: %s", algorithm)
		return nil, ErrInvalidKeyType{}
	}

	return pubKey, nil
}
예제 #11
0
// ValidatePublicKey checks that the provided public key is valid.
func ValidatePublicKey(publicKey interface{}) (bool, error) {
	switch publicKey := publicKey.(type) {
	case string:
		// at the moment we don't care about the pub interface

		decPubKey, z := pem.Decode([]byte(publicKey))
		if decPubKey == nil {
			err := fmt.Errorf("Public key does not validate: %s", z)
			return false, err
		}
		// Add the header to PKCS#1 public keys
		if strings.HasPrefix(publicKey, "-----BEGIN RSA PUBLIC KEY-----") && len(decPubKey.Bytes) == 270 {
			pkcs8head := []byte{0x30, 0x82, 0x01, 0x22, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x82, 0x01, 0x0f, 0x00}
			pkcs8head = append(pkcs8head, decPubKey.Bytes...)
			decPubKey.Bytes = pkcs8head
		}
		if _, err := x509.ParsePKIXPublicKey(decPubKey.Bytes); err != nil {
			nerr := fmt.Errorf("Public key did not validate: %s", err.Error())
			return false, nerr
		}
		return true, nil
	default:
		err := fmt.Errorf("Public key does not validate")
		return false, err
	}
}
예제 #12
0
// HeaderDecrypt decrypts the encrypted header with the client or user's public
// key for validating requests. This function is informed by chef-golang's
// privateDecrypt function.
func HeaderDecrypt(pkPem string, data string) ([]byte, error) {
	block, _ := pem.Decode([]byte(pkPem))
	if block == nil {
		return nil, fmt.Errorf("Invalid block size for '%s'", pkPem)
	}
	pubKey, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		return nil, err
	}
	decData, perr := base64.StdEncoding.DecodeString(data)
	if perr != nil {
		return nil, perr
	}
	dec, derr := decrypt(pubKey.(*rsa.PublicKey), decData)
	if derr != nil {
		return nil, derr
	}
	/* skip past the 0xff padding added to the header before encrypting. */
	skip := 0
	for i := 2; i < len(dec); i++ {
		if dec[i] == 0xff && dec[i+1] == 0 {
			skip = i + 2
			break
		}
	}
	return dec[skip:], nil
}
예제 #13
0
func getPublicKey() *rsa.PublicKey {
	//settings.Get().PublicKeyPath
	///Users/amosunsunday/Documents/Official/xtremepay/Sources/services/src/xtremepay.com/backoffice/security/settings/keys/public_key.pub
	publicKeyFile, err := os.Open("/Users/amosunsunday/Documents/Official/xtremepay/Sources/services/src/xtremepay.com/backoffice/security/settings/keys/public_key.pub")
	if err != nil {
		panic(err)
	}

	pemfileinfo, _ := publicKeyFile.Stat()
	var size int64 = pemfileinfo.Size()
	pembytes := make([]byte, size)

	buffer := bufio.NewReader(publicKeyFile)
	_, err = buffer.Read(pembytes)

	data, _ := pem.Decode([]byte(pembytes))

	publicKeyFile.Close()

	publicKeyImported, err := x509.ParsePKIXPublicKey(data.Bytes)

	if err != nil {
		panic(err)
	}

	rsaPub, ok := publicKeyImported.(*rsa.PublicKey)

	if !ok {
		panic(err)
	}

	return rsaPub
}
예제 #14
0
func (m *MobilePayNotify) VerifySign() (bool, error) {

	// 待签名数据
	data := m.signStr()
	// Parse public key into rsa.PublicKey
	PEMBlock, _ := pem.Decode([]byte(pubKeyPEM))
	if PEMBlock == nil {
		return false, errors.New("Could not parse Public Key PEM")
	}
	if PEMBlock.Type != "PUBLIC KEY" {
		return false, errors.New("Found wrong key type")
	}
	pubkey, err := x509.ParsePKIXPublicKey(PEMBlock.Bytes)
	if err != nil {
		return false, err
	}

	// compute the sha1
	h := sha1.New()
	h.Write([]byte(data))

	signature, err := base64.StdEncoding.DecodeString(m.Sign)
	if err != nil {
		return false, err
	}

	// Verify
	err = rsa.VerifyPKCS1v15(pubkey.(*rsa.PublicKey), crypto.SHA1, h.Sum(nil), signature)
	if err != nil {
		return false, err
	}

	return true, nil
}
예제 #15
0
// Deserialize an RSA public key from wire format
func RSAPubKeyFromWire(data []byte) (pub *rsa.PublicKey, err error) {
	pk, err := x509.ParsePKIXPublicKey(data)
	if err == nil {
		pub = pk.(*rsa.PublicKey)
	}
	return
}
예제 #16
0
// UnmarshalJSON parses a simple JSON format for log descriptions.  Both the
// URI and the public key are expected to be strings.  The public key is a
// base64-encoded PKIX public key structure.
func (logDesc *LogDescription) UnmarshalJSON(data []byte) error {
	var rawLogDesc rawLogDescription
	if err := json.Unmarshal(data, &rawLogDesc); err != nil {
		return fmt.Errorf("Failed to unmarshal log description, %s", err)
	}
	logDesc.URI = rawLogDesc.URI
	// Load Key
	pkBytes, err := base64.StdEncoding.DecodeString(rawLogDesc.PublicKey)
	if err != nil {
		return fmt.Errorf("Failed to decode base64 log public key")
	}
	pk, err := x509.ParsePKIXPublicKey(pkBytes)
	if err != nil {
		return fmt.Errorf("Failed to parse log public key")
	}
	ecdsaKey, ok := pk.(*ecdsa.PublicKey)
	if !ok {
		return fmt.Errorf("Failed to unmarshal log description for %s, unsupported public key type", logDesc.URI)
	}
	logDesc.PublicKey = ecdsaKey

	// Generate key hash for log ID
	pkHash := sha256.Sum256(pkBytes)
	logDesc.ID = base64.StdEncoding.EncodeToString(pkHash[:])
	if len(logDesc.ID) != 44 {
		return fmt.Errorf("Invalid log ID length [%d]", len(logDesc.ID))
	}

	return nil
}
예제 #17
0
// VerifySignature verifies in app billing signature.
// You need to prepare a public key for your Android app's in app billing
// at https://play.google.com/apps/publish/
func VerifySignature(base64EncodedPublicKey string, receipt []byte, signature string) (isValid bool, err error) {
	// prepare public key
	decodedPublicKey, err := base64.StdEncoding.DecodeString(base64EncodedPublicKey)
	if err != nil {
		return false, fmt.Errorf("failed to decode public key")
	}
	publicKeyInterface, err := x509.ParsePKIXPublicKey(decodedPublicKey)
	if err != nil {
		return false, fmt.Errorf("failed to parse public key")
	}
	publicKey, _ := publicKeyInterface.(*rsa.PublicKey)

	// generate hash value from receipt
	hasher := sha1.New()
	hasher.Write(receipt)
	hashedReceipt := hasher.Sum(nil)

	// decode signature
	decodedSignature, err := base64.StdEncoding.DecodeString(signature)
	if err != nil {
		return false, fmt.Errorf("failed to decode signature")
	}

	// verify
	if err := rsa.VerifyPKCS1v15(publicKey, crypto.SHA1, hashedReceipt, decodedSignature); err != nil {
		return false, nil
	}

	return true, nil
}
예제 #18
0
func loadPublicKey(path string) (*rsa.PublicKey, error) {
	// Read the private key
	pemData, err := ioutil.ReadFile(path)
	if err != nil {
		return nil, errors.New(fmt.Sprintf("read key file: %s", err))
	}

	// Extract the PEM-encoded data block
	block, _ := pem.Decode(pemData)
	if block == nil {
		return nil, errors.New(fmt.Sprintf("bad key data: %s", "not PEM-encoded"))
	}
	if got, want := block.Type, "PUBLIC KEY"; got != want {
		return nil, errors.New(fmt.Sprintf("unknown key type %q, want %q", got, want))
	}

	// Decode the RSA private key
	pub, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		return nil, errors.New(fmt.Sprintf("bad public key: %s", err))
	}

	key, ok := pub.(*rsa.PublicKey)
	if !ok {
		return nil, errors.New(fmt.Sprintf("public key does not implement *rsa.PublicKey: %s", reflect.TypeOf(pub)))
	}

	return key, nil
}
예제 #19
0
// Used for tests. Everytime its load key from file.
func RSAEncrypt(data []byte) ([]byte, error) {
	pathToKey, cfgErr := cfg.GetStr(cfg.STR_KEYS_PATH)
	if cfgErr != nil {
		return nil, cfgErr
	}

	pemData, err := ioutil.ReadFile(pathToKey + "public_key.pem")
	if err != nil {
		return nil, err
	}
	// Extract the PEM-encoded data block
	block, _ := pem.Decode(pemData)
	if block == nil {
		return nil, errors.New("Empty block.")
	}

	// Decode the RSA public key
	key, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		return nil, err
	}
	pkey := key.(*rsa.PublicKey)
	// Encrypt the data
	out, err := rsa.EncryptPKCS1v15(rand.Reader, pkey, data)
	if err != nil {
		return nil, err
	}

	return out, nil
}
예제 #20
0
// LoadPEMPubKey attempts to load a public key from PEM.
func LoadPEMPubKey(in []byte) (crypto.PublicKey, error) {
	p, rest := pem.Decode(in)
	if p == nil || len(rest) != 0 {
		return nil, errors.New("couldn't decode public key")
	}
	return x509.ParsePKIXPublicKey(p.Bytes)
}
예제 #21
0
// Verify does the actual check.
func (v RSAPSSVerifier) Verify(key data.Key, sig []byte, msg []byte) error {
	algorithm := key.Algorithm()
	var pubKey crypto.PublicKey

	switch algorithm {
	case data.RSAx509Key:
		pemCert, _ := pem.Decode([]byte(key.Public()))
		if pemCert == nil {
			logrus.Infof("failed to decode PEM-encoded x509 certificate")
			return ErrInvalid
		}
		cert, err := x509.ParseCertificate(pemCert.Bytes)
		if err != nil {
			logrus.Infof("failed to parse x509 certificate: %s\n", err)
			return ErrInvalid
		}
		pubKey = cert.PublicKey
	case data.RSAKey:
		var err error
		pubKey, err = x509.ParsePKIXPublicKey(key.Public())
		if err != nil {
			logrus.Infof("failed to parse public key: %s\n", err)
			return ErrInvalid
		}
	default:
		logrus.Infof("invalid key type for RSAPSS verifier: %s", algorithm)
		return ErrInvalid
	}

	digest := sha256.Sum256(msg)

	return verifyPSS(pubKey, digest[:], sig)
}
예제 #22
0
// Parse PEM encoded PKCS1 or PKCS8 public key
func ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error) {
	var err error

	// Parse PEM block
	var block *pem.Block
	if block, _ = pem.Decode(key); block == nil {
		return nil, errors.New("Invalid Key: Key must be PEM encoded PKCS1 or PKCS8 private key")
	}

	// Parse the key
	var parsedKey interface{}
	if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil {
		if cert, err := x509.ParseCertificate(block.Bytes); err == nil {
			parsedKey = cert.PublicKey
		} else {
			return nil, err
		}
	}

	var pkey *rsa.PublicKey
	var ok bool
	if pkey, ok = parsedKey.(*rsa.PublicKey); !ok {
		return nil, errors.New("Key is not a valid RSA public key")
	}

	return pkey, nil
}
예제 #23
0
func UnmarshalPublicKey(b []byte) (stdcrypto.PublicKey, error) {
	pub, err := x509.ParsePKIXPublicKey(b)
	if pub == nil { //maybe pub==err==nil
		return nil, nvl(err, UNRECOGNIZED_SYMBOLS).(error)
	}
	return pub.(stdcrypto.PublicKey), nil
}
예제 #24
0
파일: rsa.go 프로젝트: HYQMartin/mybeeim
//********公钥加密 注意:os.Open 相对路径会报错,且这一块应打包在客户端
func RsaEncrypt(origData []byte, publicKey []byte) ([]byte, error) {
	/*file1, err := os.Open("D:/myproject/src/beeim/cfg/public.pem")
	if err != nil {
		panic(err)
	}
	defer file1.Close()
	publicKey, err := io util.ReadAll(file1)
	if err != nil {
		panic(err)
	}*/
	/*publicKey := []byte(`-----BEGIN PUBLIC KEY-----
	MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCbmNv4mBsuPb4xzuUwT2TxEbjG
	va76zLrF//NRiUKV/T8mKtfv/R+Q+7FGwYkZbDNl5bO0UF0MR69u8ZE1cBAzn74z
	JGqQVs9QrRgp3VTYM/9s8nOvogcz6+l1amEY+djV3iztHOxyptl1Eq8d3r82kcwf
	ybxRlNMfwNhT7VpvqQIDAQAB
	-----END PUBLIC KEY-----`)*/

	block, _ := pem.Decode(publicKey)
	if block == nil {
		return nil, errors.New("public key error")
	}
	pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		return nil, err
	}
	pub := pubInterface.(*rsa.PublicKey)
	return rsa.EncryptPKCS1v15(rand.Reader, pub, origData)
}
예제 #25
0
func GetRsaPublicKeyForPkcs8PublicKeyPath(pubKeyPkcs8Path string) (*rsa.PublicKey, error) {
	var pubKey *rsa.PublicKey

	isFileGtZero, err := ioutilmore.IsFileWithSizeGtZero(pubKeyPkcs8Path)
	if err != nil {
		return pubKey, err
	} else if isFileGtZero == false {
		return pubKey, errors.New("400: key file path is zero size.")
	}

	pubKeyPkcs8Bytes, err := ioutil.ReadFile(pubKeyPkcs8Path)
	if err != nil {
		return pubKey, err
	}

	block, _ := pem.Decode(pubKeyPkcs8Bytes)
	pubKeyInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		return pubKey, err
	}

	pubKey, ok := pubKeyInterface.(*rsa.PublicKey)
	if !ok {
		return pubKey, errors.New("500: Cannot convert pub interface{} to *rsa.PublicKey")
	}
	return pubKey, nil
}
예제 #26
0
func enc(text string) {
	fmt.Println(text)
	data := []byte(text)
	block, _ := pem.Decode([]byte(key["pri"]))
	privkey, _ := x509.ParsePKCS1PrivateKey(block.Bytes)
	encData, _ := PrivateEncrypt(privkey, data)
	fmt.Println(encData)

	fmt.Println(base64.StdEncoding.EncodeToString(encData))

	block2, _ := pem.Decode([]byte(key["pub"]))
	pubinterface, rest := x509.ParsePKIXPublicKey(block2.Bytes)
	if rest != nil {
		println("parse public key fail")
		return
	}
	plaindata, err := PublicDecrypt(pubinterface.(*rsa.PublicKey), encData)
	fmt.Println("N:" + base64.StdEncoding.EncodeToString(pubinterface.(*rsa.PublicKey).N.Bytes()))
	if err != nil {
		println(err)
		return
	}
	fmt.Println(string(plaindata))

}
예제 #27
0
파일: tlsca.go 프로젝트: yhjohn163/obc-peer
// CreateCertificate requests the creation of a new enrollment certificate by the TLSCA.
//
func (tlscap *TLSCAP) CreateCertificate(ctx context.Context, in *pb.TLSCertCreateReq) (*pb.TLSCertCreateResp, error) {
	Trace.Println("grpc TLSCAP:CreateCertificate")

	id := in.Id.Id

	sig := in.Sig
	in.Sig = nil

	r, s := big.NewInt(0), big.NewInt(0)
	r.UnmarshalText(sig.R)
	s.UnmarshalText(sig.S)

	raw := in.Pub.Key
	if in.Pub.Type != pb.CryptoType_ECDSA {
		return nil, errors.New("unsupported key type")
	}
	pub, err := x509.ParsePKIXPublicKey(in.Pub.Key)
	if err != nil {
		return nil, err
	}

	hash := utils.NewHash()
	raw, _ = proto.Marshal(in)
	hash.Write(raw)
	if ecdsa.Verify(pub.(*ecdsa.PublicKey), hash.Sum(nil), r, s) == false {
		return nil, errors.New("signature does not verify")
	}

	if raw, err = tlscap.tlsca.createCertificate(id, pub.(*ecdsa.PublicKey), x509.KeyUsageDigitalSignature, in.Ts.Seconds, nil); err != nil {
		Error.Println(err)
		return nil, err
	}

	return &pb.TLSCertCreateResp{&pb.Cert{raw}, &pb.Cert{tlscap.tlsca.raw}}, nil
}
예제 #28
0
// RSAEncrypt RSA加密,将消息使用公钥加密后传给对方,由对方使用私钥解密
func RSAEncrypt(publicKey, message []byte) ([]byte, error) {
	block, _ := pem.Decode(publicKey)
	if block == nil {
		return nil, errors.New("public key error")
	}
	pubIntf, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		return nil, err
	}
	pub := pubIntf.(*rsa.PublicKey)
	maxLen := (pub.N.BitLen()+7)/8 - 11 // 每次加密明文的最大长度

	var data []byte
	// 计算密文的最大长度(加密后密文要比明文长,maxLen+11就是加密后密文的最大长度)
	if m := len(message); m%maxLen == 0 {
		data = make([]byte, 0, m/maxLen*(maxLen+11))
	} else {
		data = make([]byte, 0, (m/maxLen+1)*(maxLen+11))
	}
	for {
		if l := len(message); l == 0 {
			break
		} else if l < maxLen {
			maxLen = l
		}
		d, err := rsa.EncryptPKCS1v15(rand.Reader, pub, message[0:maxLen])
		if err != nil {
			return nil, err
		}
		message = message[maxLen:]
		data = append(data, d...)
	}
	return data, nil
}
예제 #29
0
파일: example_test.go 프로젝트: achanda/go
func ExampleDecode() {
	var pubPEMData = []byte(`
-----BEGIN PUBLIC KEY-----
MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAlRuRnThUjU8/prwYxbty
WPT9pURI3lbsKMiB6Fn/VHOKE13p4D8xgOCADpdRagdT6n4etr9atzDKUSvpMtR3
CP5noNc97WiNCggBjVWhs7szEe8ugyqF23XwpHQ6uV1LKH50m92MbOWfCtjU9p/x
qhNpQQ1AZhqNy5Gevap5k8XzRmjSldNAFZMY7Yv3Gi+nyCwGwpVtBUwhuLzgNFK/
yDtw2WcWmUU7NuC8Q6MWvPebxVtCfVp/iQU6q60yyt6aGOBkhAX0LpKAEhKidixY
nP9PNVBvxgu3XZ4P36gZV6+ummKdBVnc3NqwBLu5+CcdRdusmHPHd5pHf4/38Z3/
6qU2a/fPvWzceVTEgZ47QjFMTCTmCwNt29cvi7zZeQzjtwQgn4ipN9NibRH/Ax/q
TbIzHfrJ1xa2RteWSdFjwtxi9C20HUkjXSeI4YlzQMH0fPX6KCE7aVePTOnB69I/
a9/q96DiXZajwlpq3wFctrs1oXqBp5DVrCIj8hU2wNgB7LtQ1mCtsYz//heai0K9
PhE4X6hiE0YmeAZjR0uHl8M/5aW9xCoJ72+12kKpWAa0SFRWLy6FejNYCYpkupVJ
yecLk/4L1W0l6jQQZnWErXZYe0PNFcmwGXy1Rep83kfBRNKRy5tvocalLlwXLdUk
AIU+2GKjyT3iMuzZxxFxPFMCAwEAAQ==
-----END PUBLIC KEY-----
and some more`)

	block, rest := pem.Decode(pubPEMData)
	if block == nil || block.Type != "PUBLIC KEY" {
		log.Fatal("failed to decode PEM block containing public key")
	}

	pub, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Got a %T, with remaining data: %q", pub, rest)
	// Output: Got a *rsa.PublicKey, with remaining data: "and some more"
}
예제 #30
0
파일: cipher.go 프로젝트: keyphact/pso2-go
func loadKey(reader io.Reader) (interface{}, error) {
	data, err := ioutil.ReadAll(reader)

	if err != nil {
		return nil, err
	}

	for len(data) > 0 {
		var block *pem.Block
		block, data = pem.Decode(data)

		if block == nil {
			break
		}

		switch block.Type {
		case "RSA PRIVATE KEY":
			return x509.ParsePKCS1PrivateKey(block.Bytes)

		case "PRIVATE KEY":
			return x509.ParsePKCS8PrivateKey(block.Bytes)

		case "RSA PUBLIC KEY":
			fallthrough
		case "PUBLIC KEY":
			return x509.ParsePKIXPublicKey(block.Bytes)
		}
	}

	return nil, errors.New("no key found")
}