當前位置: 首頁>>代碼示例>>Golang>>正文


Golang rsa.EncryptPKCS1v15函數代碼示例

本文整理匯總了Golang中crypto/rsa.EncryptPKCS1v15函數的典型用法代碼示例。如果您正苦於以下問題:Golang EncryptPKCS1v15函數的具體用法?Golang EncryptPKCS1v15怎麽用?Golang EncryptPKCS1v15使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了EncryptPKCS1v15函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: EncryptRSA

//EncryptRSA encrypt given data with RSA algorithm
func EncryptRSA(data []byte) []byte {
	if data == nil {
		return nil
	}
	publicKey := []byte(PublicKey)
	if !ginutil.IsProduction() {
		publicKey = []byte(TestPublicKey)
	}
	block, _ := pem.Decode(publicKey)
	if block == nil {
		return nil
	}
	pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		return nil
	}
	pub := pubInterface.(*rsa.PublicKey)
	encrypted := make([]byte, 0, len(data))
	for i := 0; i < len(data); i += 117 {
		if i+117 < len(data) {
			partial, err1 := rsa.EncryptPKCS1v15(rand.Reader, pub, data[i:i+117])
			if err1 != nil {
				return nil
			}
			encrypted = append(encrypted, partial...)
		} else {
			partial, err1 := rsa.EncryptPKCS1v15(rand.Reader, pub, data[i:])
			if err1 != nil {
				return nil
			}
			encrypted = append(encrypted, partial...)
		}
	}
	return encrypted
}
開發者ID:jameswei,項目名稱:zmopenapi-sdk-golang,代碼行數:36,代碼來源:crypto_util.go

示例2: genKey

// Generates a symmetric key and encrypts the verification token
func (client *Client) genKey() (err error) {
	if client.DebugWriter != nil {
		fmt.Fprintf(client.DebugWriter, "Decoding public key\n")
	}

	var pki publicKeyInfo
	_, err = asn1.Unmarshal(client.serverKeyMessage, &pki)
	if err != nil {
		return err
	}

	client.serverKey = new(rsa.PublicKey)
	_, err = asn1.Unmarshal(pki.SubjectPublicKey.Bytes, client.serverKey)
	if err != nil {
		return err
	}

	if client.DebugWriter != nil {
		fmt.Fprintf(client.DebugWriter, "Generating encryption key\n")
	}

	/*
		client.sharedSecret = make([]byte, 16)

		_, err = rand.Reader.Read(client.sharedSecret)
		if err != nil {
			return err
		}
	*/

	client.sharedSecret = []byte("1234567812345678")

	if client.DebugWriter != nil {
		fmt.Fprintf(client.DebugWriter, "Encrypting verification token\n")
	}

	client.encryptedVerifyToken, err = rsa.EncryptPKCS1v15(rand.Reader, client.serverKey, client.serverVerifyToken)
	if err != nil {
		return err
	}

	if client.DebugWriter != nil {
		fmt.Fprintf(client.DebugWriter, "Encrypting shared secret\n")
	}

	client.encryptedSharedSecret, err = rsa.EncryptPKCS1v15(rand.Reader, client.serverKey, client.sharedSecret)
	if err != nil {
		return err
	}

	return nil
}
開發者ID:Syfaro,項目名稱:mc,代碼行數:53,代碼來源:server.go

示例3: GenerateCredentials

func GenerateCredentials(username, password, rawPem []byte) (cred string, err error) {
	ms := time.Now().UnixNano() / 1e6
	unixStr := strconv.FormatInt(ms, 10)

	userBase64 := base64.StdEncoding.EncodeToString(username)
	passBase64 := base64.StdEncoding.EncodeToString(password)
	timeBase64 := base64.StdEncoding.EncodeToString([]byte(unixStr))

	formated := fmt.Sprintf("%s:%s:%s", userBase64, passBase64, timeBase64)

	block, _ := pem.Decode(rawPem)
	if block == nil {
		err = errors.New("Could not Decode PEM")
		return
	}

	pubKeyVal, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		return
	}

	rsaPubKey, ok := pubKeyVal.(*rsa.PublicKey)
	if !ok {
		err = errors.New("Could not make DER to an RSA PublicKey")
		return
	}

	encr, err := rsa.EncryptPKCS1v15(rand.Reader, rsaPubKey, []byte(formated))
	if err != nil {
		return
	}

	cred = base64.StdEncoding.EncodeToString(encr)
	return
}
開發者ID:gurre,項目名稱:nordnet,代碼行數:35,代碼來源:util.go

示例4: HybridEncrypt

func HybridEncrypt(publicKeyFile []byte, plaintextBytes []byte) (string, error) {
	secretKey := GenerateSecretKey()
	encryptedString, err := AesEncrypt(secretKey, plaintextBytes)
	if err != nil {
		log.Fatal("failed to GcmEncrypt: " + err.Error())
	}

	publicKeyUntyped, err := x509.ParsePKIXPublicKey(publicKeyFile)
	if err != nil {
		log.Fatal("failed to parse certificate: " + err.Error())
	}
	publicKey := publicKeyUntyped.(*rsa.PublicKey)

	encryptedPublicKeyBytes, err := rsa.EncryptPKCS1v15(rand.Reader, publicKey, secretKey)
	if err != nil {
		log.Fatal("failed to wrap" + err.Error())
	}

	var buffer bytes.Buffer
	buffer.WriteString(base64.StdEncoding.EncodeToString(encryptedPublicKeyBytes))
	buffer.WriteString(hybridDelimiter)
	buffer.WriteString(encryptedString)

	return buffer.String(), nil
}
開發者ID:gravieinc,項目名稱:aws-crypto-tools-go,代碼行數:25,代碼來源:hybrid.go

示例5: NewDecryptTest

// NewDecryptTest generates an RSA decryption test.
func NewDecryptTest(decrypter crypto.Decrypter) testapi.TestFunc {
	ptxt := []byte("Test Plaintext")
	r := rand.Reader

	return func() (err error) {
		var c, m []byte
		if c, err = rsa.EncryptPKCS1v15(r, decrypter.Public().(*rsa.PublicKey), ptxt); err != nil {
			return
		}

		if m, err = decrypter.Decrypt(r, c, &rsa.PKCS1v15DecryptOptions{}); err != nil {
			return
		}
		if bytes.Compare(ptxt, m) != 0 {
			return errors.New("rsa decrypt failed")
		}

		if m, err = decrypter.Decrypt(r, c, &rsa.PKCS1v15DecryptOptions{SessionKeyLen: len(ptxt)}); err != nil {
			return
		}
		if bytes.Compare(ptxt, m) != 0 {
			return errors.New("rsa decrypt failed")
		}

		if m, err = decrypter.Decrypt(r, c, &rsa.PKCS1v15DecryptOptions{SessionKeyLen: len(ptxt) + 1}); err != nil {
			return
		}
		if bytes.Compare(ptxt, m) == 0 {
			return errors.New("rsa decrypt suceeded despite incorrect SessionKeyLen")
		}
		return nil
	}
}
開發者ID:carriercomm,項目名稱:gokeyless,代碼行數:34,代碼來源:tests.go

示例6: RsaEncrypt

//********公鑰加密 注意: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)
}
開發者ID:HYQMartin,項目名稱:mybeeim,代碼行數:29,代碼來源:rsa.go

示例7: EncryptPKCS1v15

func EncryptPKCS1v15(msg []byte) string {
	certPEMBlock, err := ioutil.ReadFile("./key.pem")
	if err != nil {
		log.Fatal("PEM error %v", err)
	}

	var keyDERBlock *pem.Block
	keyDERBlock, certPEMBlock = pem.Decode(certPEMBlock)

	var publickey *rsa.PublicKey
	if key, err := x509.ParsePKIXPublicKey(keyDERBlock.Bytes); err == nil {
		publickey = key.(*rsa.PublicKey)
		log.Printf("got a key")
	}

	encryptedmsg, err := rsa.EncryptPKCS1v15(rand.Reader, publickey, msg)

	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	fmt.Printf("OAEP encrypted [%s] to \n[%x]\n", string(msg), encryptedmsg)
	fmt.Println()

	return base64.URLEncoding.EncodeToString(encryptedmsg)
}
開發者ID:mikechack,項目名稱:wsrouter,代碼行數:27,代碼來源:oauth.go

示例8: TestGeneratePem_GeneratePemThenCheckIfValidPrivateKey

func TestGeneratePem_GeneratePemThenCheckIfValidPrivateKey(t *testing.T) {
	privateKey := PrivateKey()
	privatePem := GeneratePrivatePem(privateKey)
	pemBlock, _ := pem.Decode(privatePem)
	if pemBlock == nil {
		t.Fatal("The pem key didn't transfer back into a block")
	}
	validKey, err := x509.ParsePKCS1PrivateKey(pemBlock.Bytes)
	if err != nil {
		t.Fatal("The parser failed to create a key")
	}
	output := validKey.Validate()
	if output != nil {
		t.Fatal("The key that was created is not valid")
	}

	snippet := "Hello, world!"
	publicKey := privateKey.PublicKey
	publicEncrypt, _ := rsa.EncryptPKCS1v15(rand.Reader, &publicKey, []byte(snippet))

	privateDecrypt, err := rsa.DecryptPKCS1v15(rand.Reader, validKey, publicEncrypt)
	if err != nil {
		t.Fatal("Something went wrong in the decryption of publicEncrypt: ", err)
	}

	if string(privateDecrypt) != snippet {
		t.Fatal("Something didn't work in: ", privateDecrypt)
	}
}
開發者ID:amaxwellblair,項目名稱:coinage_go,代碼行數:29,代碼來源:keyGenerator_test.go

示例9: RSAEncrypt

// 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
}
開發者ID:walkline,項目名稱:GoMastersLunch,代碼行數:31,代碼來源:SimpleRSA.go

示例10: EncryptChatMessage

func (c *Controller) EncryptChatMessage() (string, error) {

	var err error

	c.r.ParseForm()

	receiver := c.r.FormValue("receiver")
	message := c.r.FormValue("message")
	if len(message) > 5120 {
		return "", errors.New("incorrect message")
	}

	publicKey, err := c.Single("SELECT public_key_0 FROM users WHERE user_id  =  ?", receiver).Bytes()
	if err != nil {
		return "", utils.ErrInfo(err)
	}

	if len(publicKey) > 0 {
		pub, err := utils.BinToRsaPubKey(publicKey)
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		enc_, err := rsa.EncryptPKCS1v15(rand.Reader, pub, []byte(message))
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		return utils.JsonAnswer(string(utils.BinToHex(enc_)), "success").String(), nil
	} else {
		return utils.JsonAnswer("Incorrect user_id", "error").String(), nil
	}

}
開發者ID:dzyk,項目名稱:dcoin-go,代碼行數:32,代碼來源:encrypt_chat_message.go

示例11: RSAEncrypt

// 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
}
開發者ID:zhangyuchen0411,項目名稱:goutil,代碼行數:35,代碼來源:rsa.go

示例12: generateClientKeyExchange

func (ka *rsaKeyAgreement) generateClientKeyExchange(config *Config, clientHello *clientHelloMsg, cert *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error) {
	preMasterSecret := make([]byte, 48)
	vers := clientHello.vers
	if config.Bugs.RsaClientKeyExchangeVersion != 0 {
		vers = config.Bugs.RsaClientKeyExchangeVersion
	}
	vers = versionToWire(vers, clientHello.isDTLS)
	preMasterSecret[0] = byte(vers >> 8)
	preMasterSecret[1] = byte(vers)
	_, err := io.ReadFull(config.rand(), preMasterSecret[2:])
	if err != nil {
		return nil, nil, err
	}

	encrypted, err := rsa.EncryptPKCS1v15(config.rand(), cert.PublicKey.(*rsa.PublicKey), preMasterSecret)
	if err != nil {
		return nil, nil, err
	}
	ckx := new(clientKeyExchangeMsg)
	if clientHello.vers != VersionSSL30 && !config.Bugs.SSL3RSAKeyExchange {
		ckx.ciphertext = make([]byte, len(encrypted)+2)
		ckx.ciphertext[0] = byte(len(encrypted) >> 8)
		ckx.ciphertext[1] = byte(len(encrypted))
		copy(ckx.ciphertext[2:], encrypted)
	} else {
		ckx.ciphertext = encrypted
	}
	return preMasterSecret, ckx, nil
}
開發者ID:hoangmichel,項目名稱:webrtc,代碼行數:29,代碼來源:key_agreement.go

示例13: main

func main() {
	var primes []uint64 = prime.PrimeSieveBatch{BatchSize: 100}.GetPrimes(10000)
	var p, q uint64 = /*uint64(104723), uint64(104729) */ primes[len(primes)-2], primes[len(primes)-1]
	fmt.Println(p, q)
	var mod int64 = int64(p * q)
	fmt.Println(mod)
	var puk, prk = /*int(65537), uint64(10195862609) */ KeyGenerator1{}.KeyGen(p, q)
	fmt.Println(puk, prk)

	b := []byte("Hi")
	var pub rsa.PublicKey = rsa.PublicKey{N: big.NewInt(mod), E: puk}
	var priv rsa.PrivateKey = rsa.PrivateKey{PublicKey: pub}
	priv.D = big.NewInt(int64(prk))
	priv.Primes = []*big.Int{big.NewInt(int64(p)), big.NewInt(int64(q))}

	fmt.Println(len(b))
	fmt.Printf("% x\n", b)

	//h := md5.New()
	enc, erre := rsa.EncryptPKCS1v15(rand.Reader, &pub, b)
	//h.Reset()
	dec, errd := rsa.DecryptPKCS1v15(rand.Reader, &priv, b)

	//fmt.Println(64 - 11)
	fmt.Printf("%s\n", erre)
	fmt.Printf("%s\n", errd)
	fmt.Printf("% x\n", enc)
	fmt.Printf("% x\n", dec)
}
開發者ID:frankbryce,項目名稱:crypto-explore,代碼行數:29,代碼來源:main.go

示例14: RSAEncrypt

// RSAEncrypt encrypts a content by a public key
func RSAEncrypt(keyBytes []byte, contentBytes []byte) ([]byte, error) {
	pubKey, err := getPubKey(keyBytes)
	if err != nil {
		return nil, err
	}

	return rsa.EncryptPKCS1v15(rand.Reader, pubKey, contentBytes)
}
開發者ID:pombredanne,項目名稱:dockyard,代碼行數:9,代碼來源:common.go

示例15: encryptPreMasterSecret

//See: 7.4.7.1.  RSA-Encrypted Premaster Secret Message
func encryptPreMasterSecret(preMasterSecret []byte, pub *rsa.PublicKey) (*encryptedPreMasterSecretBody, error) {
	out, err := rsa.EncryptPKCS1v15(rand.Reader, pub, preMasterSecret)
	if err != nil {
		return nil, err
	}

	return &encryptedPreMasterSecretBody{out}, nil
}
開發者ID:twstrike,項目名稱:toyls,代碼行數:9,代碼來源:handshake.go


注:本文中的crypto/rsa.EncryptPKCS1v15函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。