コード例 #1
0
//DecryptRSA decrypt given []byte with RSA algorithm
func DecryptRSA(data []byte) []byte {
	if data == nil {
		return nil
	}
	privateKey := []byte(PrivateKey)
	if !ginutil.IsProduction() {
		privateKey = []byte(TestPrivateKey)
	}
	block, _ := pem.Decode(privateKey)
	if block == nil {
		return nil
	}
	privInterface, err := x509.ParsePKCS8PrivateKey(block.Bytes)
	if err != nil {
		return nil
	}
	priv := privInterface.(*rsa.PrivateKey)
	decrypted := make([]byte, 0, len(data))
	for i := 0; i < len(data); i += 128 {
		if i+128 < len(data) {
			partial, err1 := rsa.DecryptPKCS1v15(rand.Reader, priv, data[i:i+128])
			if err1 != nil {
				return nil
			}
			decrypted = append(decrypted, partial...)
		} else {
			partial, err1 := rsa.DecryptPKCS1v15(rand.Reader, priv, data[i:])
			if err1 != nil {
				return nil
			}
			decrypted = append(decrypted, partial...)
		}
	}
	return decrypted
}
コード例 #2
0
ファイル: clientencryption.go プロジェクト: kierdavis/proxy
func (cem *clientEncryptionManager) handleEncryptionResponse(packet *LS1EncryptionResponsePacket) (err error) {
	cem.sharedSecret, err = rsa.DecryptPKCS1v15(crand.Reader, cem.gem.privateKey, packet.EncryptedSharedSecret)
	if err != nil {
		return err
	}

	returnedVerifyToken, err := rsa.DecryptPKCS1v15(crand.Reader, cem.gem.privateKey, packet.EncryptedVerifyToken)
	if err != nil {
		return err
	}

	if len(cem.verifyToken) != len(returnedVerifyToken) {
		return fmt.Errorf("Authentication failure")
	}

	var diff uint8
	for i := 0; i < len(cem.verifyToken); i++ {
		diff |= cem.verifyToken[i] ^ returnedVerifyToken[i]
	}

	if diff != 0 {
		return fmt.Errorf("Authentication failure")
	}

	return nil
}
コード例 #3
0
ファイル: handle_fc.go プロジェクト: KellyLSB/minero-go
// HandleFC handles incoming requests of packet 0xFC: EncryptionKeyResponse
func HandleFC(server *Server, sender *player.Player) {
	pkt := new(packet.EncryptionKeyResponse)
	pkt.ReadFrom(sender.Conn)

	// Decrypt shared secret and token with server's private key.
	var secret, token []byte
	// var err error
	secret, _ = rsa.DecryptPKCS1v15(rand.Reader, server.PrivateKey(), pkt.Secret)
	token, _ = rsa.DecryptPKCS1v15(rand.Reader, server.PrivateKey(), pkt.Token)

	// Ensure token matches
	if !bytes.Equal(token, sender.Token) {
		log.Println("Tokens don't match.")
		r := &packet.Disconnect{Reason: ReasonPiratedGame}
		r.WriteTo(sender.Conn)
		return
	}

	// Ensure player is legit
	if !server.CheckUser(sender.Name, secret) {
		log.Println("Failed to verify username!")
		r := packet.Disconnect{"Failed to verify username!"}
		r.WriteTo(sender.Conn)
		return
	}

	// Send empty EncryptionKeyResponse
	r := new(packet.EncryptionKeyResponse)
	r.WriteTo(sender.Conn)

	// Start AES/CFB8 stream encryption
	sender.OnlineMode(true, secret)
	log.Println("Enabling encryption.")
}
コード例 #4
0
ファイル: connection_test.go プロジェクト: jeffh/mc
func TestCanNegotiateEncryptedConnection(t *testing.T) {
	c, rbuf, wbuf := createConnection()
	sessionRecorder := session.NewRecorderClient()
	priv, pub, err := createPPK()
	Expect(t, err, ToBeNil)
	verifyToken := []byte{1, 2, 3, 4}

	// server gets handshake, sends EKRequest
	Expect(t, rbuf, ToWritePacket, &EncryptionKeyRequest{
		ServerID:    "-", // no user verification server ?
		PublicKey:   pub,
		VerifyToken: verifyToken,
	})
	// server gets EKResponse, returns empty EKResponse
	Expect(t, rbuf, ToWritePacket, &EncryptionKeyResponse{
		SharedSecret: []byte{},
		VerifyToken:  []byte{},
	})
	// server promotes to encrypted socket

	handshake := &Handshake{
		Version:  47,
		Username: "******",
		Hostname: "localhost",
		Port:     25565,
	}
	secret := []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}
	err = EstablishEncryptedConnection(c, handshake, secret, sessionRecorder)

	Expect(t, err, ToBeNil)

	// client should send handshake
	Expect(t, wbuf, ToReadPacket, handshake)
	// client should send EKResponse
	p, err := wbuf.ReadPacket()
	Expect(t, err, ToBeNil)
	ekRes, ok := p.(*EncryptionKeyResponse)
	Expect(t, ok, ToBeTrue)

	// we need to decrypt the fields
	dVerifyToken, err := rsa.DecryptPKCS1v15(rand.Reader, priv, ekRes.VerifyToken)
	Expect(t, err, ToBeNil)
	Expect(t, dVerifyToken, ToEqual, verifyToken)
	dSecret, err := rsa.DecryptPKCS1v15(rand.Reader, priv, ekRes.SharedSecret)
	Expect(t, err, ToBeNil)
	Expect(t, dSecret, ToEqual, secret)

	// shouldn't have any extra data
	Expect(t, rbuf.IsEmpty(), ToBeTrue)
	Expect(t, wbuf.IsEmpty(), ToBeTrue)
	// connection should be modified
	Expect(t, c.IsEncrypted(), ToBeTrue)
	Expect(t, c.ServerID, ToBe, "-")
	Expect(t, c.Encryption.SharedKey, ToEqual, secret)
}
コード例 #5
0
ファイル: rsa_test.go プロジェクト: releasifier/releasifier
func TestDecrypt(t *testing.T) {
	block, rest := pem.Decode(testData[0].privateKey)

	if len(rest) > 0 {
		t.Error("extra data")
	}

	der, err := x509.DecryptPEMBlock(block, []byte(testData[0].passphrase))

	if err != nil {
		t.Error("decrypt failed: ", err)
	}

	var privateKey *rsa.PrivateKey
	if privateKey, err = x509.ParsePKCS1PrivateKey(der); err != nil {
		t.Error("private key failed: ", err)
	}

	b, _ := base64.StdEncoding.DecodeString(testData[0].encryptedMessage)

	decrypted, err := rsa.DecryptPKCS1v15(rand.Reader, privateKey, b)

	if err != nil {
		t.Error("failed to decrypt, ", err)
	}

	assert.Equal(t, testData[0].decryptedMessage, string(decrypted), "should be the same")
}
コード例 #6
0
func HybridDecrypt(encryptedPrivateKey []byte, awsRegion string, encryptionContext map[string]*string, base64EncryptedText string) (string, error) {
	sections := strings.Split(base64EncryptedText, hybridDelimiter)

	encryptedSecretKey, err := base64.StdEncoding.DecodeString(sections[0])
	if err != nil {
		log.Fatal("Error decoding secret key" + err.Error())
	}

	aesEncryptedText := sections[1]

	privateKey, err := getPrivateKey(encryptedPrivateKey, awsRegion, encryptionContext)
	if err != nil {
		log.Fatal("Can't get private key - " + err.Error())
	}

	secretKey, err := rsa.DecryptPKCS1v15(rand.Reader, privateKey, encryptedSecretKey)
	if err != nil {
		log.Fatal("Can't decrypt AES key - " + err.Error())
	}

	plaintext, err := AesDecrypt(secretKey, aesEncryptedText)
	if err != nil {
		log.Fatal("Can't decrypt plaintext - " + err.Error())
	}

	return plaintext, nil
}
コード例 #7
0
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)
	}
}
コード例 #8
0
ファイル: main.go プロジェクト: frankbryce/crypto-explore
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)
}
コード例 #9
0
ファイル: rsa.go プロジェクト: zhangyuchen0411/goutil
// RSADecrypt RSA解密
func RSADecrypt(privateKey, data []byte) ([]byte, error) {
	block, _ := pem.Decode(privateKey)
	if block == nil {
		return nil, errors.New("private key error")
	}
	pri, err := x509.ParsePKCS1PrivateKey(block.Bytes)
	if err != nil {
		return nil, err
	}
	maxLen := (pri.PublicKey.N.BitLen() + 7) / 8 // 每次解密 密文的最大长度

	var message []byte
	// 计算明文的最大长度(解密后明文要比密文短,maxLen-11就是加密是明文的最大长度)
	if m := len(data); m%maxLen == 0 {
		message = make([]byte, 0, m/maxLen*(maxLen-11))
	} else {
		message = make([]byte, 0, (m/maxLen+1)*(maxLen-11))
	}
	for {
		if l := len(data); l == 0 {
			break
		} else if l < maxLen {
			maxLen = l
		}
		d, err := rsa.DecryptPKCS1v15(rand.Reader, pri, data[0:maxLen])
		if err != nil {
			return nil, err
		}
		data = data[maxLen:]
		message = append(message, d...)
	}
	return message, nil
}
コード例 #10
0
ファイル: rsa.go プロジェクト: HYQMartin/mybeeim
//********私钥解密  注意:相对路径读取还没解决,这块不能出现在客户端,否则暴露私钥
func RsaDecrypt(ciphertext []byte) ([]byte, error) {
	/*file2, err := os.Open("D:/myproject/src/beeim/cfg/private.pem")
	if err != nil {
		panic(err)
	}
	defer file2.Close()
	privateKey, err := ioutil.ReadAll(file2)
	if err != nil {
		panic(err)
	}*/
	privateKey := []byte(`-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQCbmNv4mBsuPb4xzuUwT2TxEbjGva76zLrF//NRiUKV/T8mKtfv
/R+Q+7FGwYkZbDNl5bO0UF0MR69u8ZE1cBAzn74zJGqQVs9QrRgp3VTYM/9s8nOv
ogcz6+l1amEY+djV3iztHOxyptl1Eq8d3r82kcwfybxRlNMfwNhT7VpvqQIDAQAB
AoGABdcrCp3LB2VR6lS1zaZtR48+vFcKZmeg6yW8YGcilLa41BnvmRaLRMnt0ZYa
K1YgZ8bDhBUwKPHX5/YxWSwnr3ll0yVKYPw310djZduJT/XSy2ugEpfhZEyKEKxE
sxArAI25IWHWnkKbJ1d6AfR0Rvac5v5O5rkpAiFWCXm633ECQQDBNWgqiSIOB4LQ
SkbMdElTOfv5/lPmjDyh2HgjRtUFs6nIDp9aJeJ4f5aZWN3trFJRTqku72dxclYi
8eSimqqjAkEAzio+ydoeF5NoYBBb5Gx5Uooz8dncxyMdzPE6OaOza9AuF5uw8CXg
ZFFXVPtbKJ7QzZ3DsenyCm4uhifpR8yNQwJAY8rsBJxUBJ8IiAD1VIDzppMafONJ
/piMcKPYWZAqUwmbNgOndu5+bPKpnIb0CeCpm+lfJSjuawA9UUtTZlEwtQJBAIT0
16NjqE56ATEau7h3gFKL0G4jm29NpVVbKLqtaPOZwW/2N0jYlHr9vj2PEL4ElhJU
sTUW88JoRla8fISSVXMCQQCGt4L8msE7Hb1yLJkIAE3SJXS6y6paFuBbensjKHEK
MlVlIJO2Pwz66P+w/Q+AGGGF6KvxIGViXM9ALZcP3ZQ8
-----END RSA PRIVATE KEY-----`)
	block, _ := pem.Decode(privateKey)
	if block == nil {
		return nil, errors.New("private key error!")
	}
	priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
	if err != nil {
		return nil, err
	}
	return rsa.DecryptPKCS1v15(rand.Reader, priv, ciphertext)
}
コード例 #11
0
ファイル: rsa_pkcs1v15.go プロジェクト: useidel/notary
func (alg *RsaPkcs1v15) Unwrap(encryptedCek []byte, key interface{}, cekSizeBits int, header map[string]interface{}) (cek []byte, err error) {
	if privKey, ok := key.(*rsa.PrivateKey); ok {
		return rsa.DecryptPKCS1v15(rand.Reader, privKey, encryptedCek)
	}

	return nil, errors.New("RsaPkcs1v15.Unwrap(): expected key to be '*rsa.PrivateKey'")
}
コード例 #12
0
ファイル: step_get_password.go プロジェクト: c12simple/packer
func decryptPasswordDataWithPrivateKey(passwordData string, pemBytes []byte) (string, error) {
	encryptedPasswd, err := base64.StdEncoding.DecodeString(passwordData)
	if err != nil {
		return "", err
	}

	block, _ := pem.Decode(pemBytes)
	var asn1Bytes []byte
	if _, ok := block.Headers["DEK-Info"]; ok {
		return "", errors.New("encrypted private key isn't yet supported")
		/*
			asn1Bytes, err = x509.DecryptPEMBlock(block, password)
			if err != nil {
				return "", err
			}
		*/
	} else {
		asn1Bytes = block.Bytes
	}

	key, err := x509.ParsePKCS1PrivateKey(asn1Bytes)
	if err != nil {
		return "", err
	}

	out, err := rsa.DecryptPKCS1v15(nil, key, encryptedPasswd)
	if err != nil {
		return "", err
	}

	return string(out), nil
}
コード例 #13
0
ファイル: encrypted_key.go プロジェクト: ContiGuy/conti-gui
// Decrypt decrypts an encrypted session key with the given private key. The
// private key must have been decrypted first.
// If config is nil, sensible defaults will be used.
func (e *EncryptedKey) Decrypt(priv *PrivateKey, config *Config) error {
	var err error
	var b []byte

	// TODO(agl): use session key decryption routines here to avoid
	// padding oracle attacks.
	switch priv.PubKeyAlgo {
	case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly:
		b, err = rsa.DecryptPKCS1v15(config.Random(), priv.PrivateKey.(*rsa.PrivateKey), e.encryptedMPI1.bytes)
	case PubKeyAlgoElGamal:
		c1 := new(big.Int).SetBytes(e.encryptedMPI1.bytes)
		c2 := new(big.Int).SetBytes(e.encryptedMPI2.bytes)
		b, err = elgamal.Decrypt(priv.PrivateKey.(*elgamal.PrivateKey), c1, c2)
	default:
		err = errors.InvalidArgumentError("cannot decrypted encrypted session key with private key of type " + strconv.Itoa(int(priv.PubKeyAlgo)))
	}

	if err != nil {
		return err
	}

	e.CipherFunc = CipherFunction(b[0])
	e.Key = b[1 : len(b)-2]
	expectedChecksum := uint16(b[len(b)-2])<<8 | uint16(b[len(b)-1])
	checksum := checksumKeyMaterial(e.Key)
	if checksum != expectedChecksum {
		return errors.StructuralError("EncryptedKey checksum incorrect")
	}

	return nil
}
コード例 #14
0
ファイル: passwordadmin.go プロジェクト: wulinxu/KeyAdmin-go
func _passwordDecoding(encodedpassword, passpharse []byte, priblock *pem.Block) (password []byte, err error) {
	//decode with base64
	_encodedpassword, err := base64.StdEncoding.DecodeString(string(encodedpassword))
	if err != nil {
		return
	}

	//compare to private key
	priByte, err := x509.DecryptPEMBlock(priblock, passpharse)
	if err != nil {
		return
	}

	pri, err := x509.ParsePKCS1PrivateKey(priByte)
	if err != nil {
		return
	}
	//decode with rsa
	password, err = rsa.DecryptPKCS1v15(rand.Reader, pri, _encodedpassword)

	if err != nil {
		return
	}

	return
}
コード例 #15
0
ファイル: passwordadmin.go プロジェクト: wulinxu/KeyAdmin-go
func _passwordListDecoding(encodedpassword [][]byte, passpharse []byte, priblock *pem.Block) (password [][]byte, err error) {
	//decode with base64
	encodedpasswordList := make([][]byte, len(encodedpassword))
	for i, e := range encodedpassword {
		encodedpasswordList[i], err = base64.StdEncoding.DecodeString(string(e))
		if err != nil {
			return
		}
	}

	//compare to private key
	priByte, err := x509.DecryptPEMBlock(priblock, passpharse)
	if err != nil {
		return
	}

	pri, err := x509.ParsePKCS1PrivateKey(priByte)
	if err != nil {
		return
	}
	//decode with rsa
	password = make([][]byte, len(encodedpasswordList))
	for i, e := range encodedpasswordList {
		password[i], err = rsa.DecryptPKCS1v15(rand.Reader, pri, e)
	}

	if err != nil {
		return
	}

	return
}
コード例 #16
0
ファイル: cipher.go プロジェクト: keyphact/pso2-go
func (c *Cipher) Key(key *rsa.PrivateKey) ([]uint8, error) {
	data := make([]uint8, len(c.KeyData))
	for i := range data {
		data[i] = c.KeyData[len(c.KeyData)-i-1]
	}

	return rsa.DecryptPKCS1v15(nil, key, data)
}
コード例 #17
0
ファイル: common.go プロジェクト: pombredanne/dockyard
// RSADecrypt decrypts content by a private key
func RSADecrypt(keyBytes []byte, contentBytes []byte) ([]byte, error) {
	privKey, err := getPrivKey(keyBytes)
	if err != nil {
		return nil, err
	}

	return rsa.DecryptPKCS1v15(rand.Reader, privKey, contentBytes)
}
コード例 #18
0
ファイル: cipher.go プロジェクト: applepi-icpc/icarus
func GetNakedKey(cipher string) ([]byte, error) {
	rawCipher, err := base64.StdEncoding.DecodeString(cipher)
	if err != nil {
		return nil, err
	}

	InitPrivKey()
	return rsa.DecryptPKCS1v15(rand.Reader, privateKey, rawCipher)
}
コード例 #19
0
ファイル: jass.go プロジェクト: fatman2021/jass
func decryptSessionKey(skey []byte, privkey *rsa.PrivateKey) (session_key []byte) {
	verbose("Decrypting session key...", 2)

	session_key, err := rsa.DecryptPKCS1v15(rand.Reader, privkey, skey)
	if err != nil {
		fail("Unable to decrypt session key.")
	}

	return
}
コード例 #20
0
ファイル: rsa.go プロジェクト: jmptrader/goexample
// 解密
func RsaDecrypt(ciphertext []byte) ([]byte, error) {
	block, _ := pem.Decode(privateKey)
	if block == nil {
		return nil, errors.New("private key error!")
	}
	priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
	if err != nil {
		return nil, err
	}
	return rsa.DecryptPKCS1v15(rand.Reader, priv, ciphertext)
}
コード例 #21
0
ファイル: rsaAlgorithm.go プロジェクト: kaelliu/Miscellaneous
func (this *RsaCipher) DoDecrypt(src []byte) ([]byte, error) {
	block, _ := pem.Decode(this.PriKey)
	if block == nil {
		return nil, errors.New("private key error!")
	}
	priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
	if err != nil {
		return nil, err
	}
	return rsa.DecryptPKCS1v15(rand.Reader, priv, src)
}
コード例 #22
0
ファイル: crypto.go プロジェクト: d4l3k/upass
func (u *User) Decrypt(key *rsa.PrivateKey) error {
	if !u.Encrypted {
		return nil
	}
	decrypted, err := rsa.DecryptPKCS1v15(rand.Reader, key, []byte(u.Password))
	if err != nil {
		return err
	}
	u.Password = string(decrypted)
	u.Encrypted = false
	return nil
}
コード例 #23
0
ファイル: simplersa.go プロジェクト: cainiaocome/cry
// dont put it in client
// debase4 and then dersa, return []byte, well, mostly should be json
func DeRsaBase64(msg_encrypted string) (msg_decrypted []byte, err error) {
	private_key := get_private_key()
	//publick_key := private_key.PublicKey

	msg_debase64ed, err := base64.StdEncoding.DecodeString(msg_encrypted)
	if err != nil {
		return
	}
	msg_debase64ed_dersaed, err := rsa.DecryptPKCS1v15(rand.Reader, private_key, msg_debase64ed)
	msg_decrypted = msg_debase64ed_dersaed
	return
}
コード例 #24
0
ファイル: ut_rsa.go プロジェクト: st2py/bitcrypt
// RSA decrypt
func RsaDecrypt(privateKey []byte, ciphertext []byte) ([]byte, error) {
	block, _ := pem.Decode(privateKey)
	if block == nil {
		return nil, errors.New("private key error!")
	}
	priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
	if err != nil {
		return nil, err
	}

	k := (priv.N.BitLen() + 7) / 8
	if len(ciphertext) > k {
		o1, e1 := rsa.DecryptPKCS1v15(rand.Reader, priv, ciphertext[:k])
		o2, e2 := rsa.DecryptPKCS1v15(rand.Reader, priv, ciphertext[k:])
		if e1 != nil || e2 != nil {
			return nil, errors.New("RSA decrypt error")
		}
		return append(o1, o2...), nil
	} else {
		return rsa.DecryptPKCS1v15(rand.Reader, priv, ciphertext)
	}
}
コード例 #25
0
ファイル: results.go プロジェクト: COLDTURNIP/kubernetes
func decryptPassword(encryptedPassword string, privateKey *rsa.PrivateKey) (string, error) {
	b64EncryptedPassword := make([]byte, base64.StdEncoding.DecodedLen(len(encryptedPassword)))

	n, err := base64.StdEncoding.Decode(b64EncryptedPassword, []byte(encryptedPassword))
	if err != nil {
		return "", fmt.Errorf("Failed to base64 decode encrypted password: %s", err)
	}
	password, err := rsa.DecryptPKCS1v15(nil, privateKey, b64EncryptedPassword[0:n])
	if err != nil {
		return "", fmt.Errorf("Failed to decrypt password: %s", err)
	}

	return string(password), nil
}
コード例 #26
0
ファイル: routers.go プロジェクト: hngchiming/BTCsport
func RSADecode(ciphertext []byte) (string, error) {
	block, _ := pem.Decode(privateKey)
	if block == nil {
		return "", errors.New("private key error!")
	}
	priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
	if err != nil {
		return "", err
	}
	data, err := rsa.DecryptPKCS1v15(rand.Reader, priv, ciphertext)
	if err != nil {
		return "", err
	}
	return string(data), nil
}
コード例 #27
0
ファイル: protocol.go プロジェクト: minecrafter/go-votifier
func Deserialize(msg []byte, privateKey *rsa.PrivateKey) (*Vote, error) {
	decrypted, err := rsa.DecryptPKCS1v15(rand.Reader, privateKey, msg)
	if err != nil {
		return nil, err
	}

	elements := strings.Split(string(decrypted), "\n")
	if len(elements) != 6 {
		return nil, fmt.Errorf("Element count is invalid; wanted 6, got %d", len(elements))
	}
	if elements[0] != "VOTE" {
		return nil, fmt.Errorf("First element is incorrect; expected 'VOTE', got %s", elements[0])
	}
	return &Vote{elements[1], elements[2], elements[3], elements[4]}, nil
}
コード例 #28
0
func main() {
	if len(os.Args) != 3 {
		fmt.Fprintf(os.Stderr, "Usage: %s <path to private key> <encrypted password>\n", os.Args[0])
		os.Exit(1)
	}
	pemPath := os.Args[1]
	encryptedPasswdB64 := os.Args[2]

	encryptedPasswd, err := base64.StdEncoding.DecodeString(encryptedPasswdB64)
	if err != nil {
		panic(err)
	}

	pemBytes, err := ioutil.ReadFile(pemPath)
	if err != nil {
		panic(err)
	}

	block, _ := pem.Decode(pemBytes)
	var asn1Bytes []byte
	if _, ok := block.Headers["DEK-Info"]; ok {
		fmt.Printf("Encrypted private key. Please enter passphrase: ")
		password, err := terminal.ReadPassword(0)
		fmt.Printf("\n")
		if err != nil {
			panic(err)
		}

		asn1Bytes, err = x509.DecryptPEMBlock(block, password)
		if err != nil {
			panic(err)
		}
	} else {
		asn1Bytes = block.Bytes
	}

	key, err := x509.ParsePKCS1PrivateKey(asn1Bytes)
	if err != nil {
		panic(err)
	}

	out, err := rsa.DecryptPKCS1v15(nil, key, encryptedPasswd)
	if err != nil {
		panic(err)
	}

	fmt.Printf("Decrypted password: %s\n", string(out))
}
コード例 #29
0
ファイル: SimpleRSA.go プロジェクト: walkline/GoMastersLunch
// Used for auth.
func RSADecrypt(data []byte) ([]byte, error) {
	// Load private key if needed
	if privateKey == nil {
		err := loadPrivateKey()
		if err != nil {
			return nil, err
		}
	}

	out, err := rsa.DecryptPKCS1v15(rand.Reader, privateKey, data)
	if err != nil {
		return nil, err
	}

	return out, nil
}
コード例 #30
0
ファイル: rsa.go プロジェクト: wcgh/commons
// 私钥解密
func RsaDecryptByPri(pri_key_file string, ciphertext []byte) ([]byte, error) {
	f, e := os.Open(pri_key_file)
	if e != nil {
		fmt.Println(e.Error())
		return nil, errors.New("private key file error")
	}
	bs, _ := ioutil.ReadAll(f)
	block, _ := pem.Decode(bs)
	if block == nil {
		return nil, errors.New("private key error!")
	}
	priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
	if err != nil {
		return nil, err
	}
	return rsa.DecryptPKCS1v15(rand.Reader, priv, ciphertext)
}