コード例 #1
0
// Function check if private key could decode what public key encode
func authorize(pubkey *rsa.PublicKey, privkey_str []byte) (bool, error) {
	block, _ := pem.Decode(privkey_str)
	if block == nil {
		return false, errors.New("Provided data is not private key")
	}
	if len(block.Bytes) < 100 {
		return false, errors.New("Provided data is not private key")
	}

	privkey := new(rsa.PrivateKey)

	if block.Type == "RSA PRIVATE KEY" {

		privkey, _ = x509.ParsePKCS1PrivateKey(block.Bytes)

	} else {
		return false, errors.New("Provided data is not private key")
	}

	// Encrypt message
	eComm, err := rsa.EncryptOAEP(sha1.New(), rand.Reader, pubkey, []byte(testMessage), nil)
	if err != nil {
		return false, err
	}

	log.Println("Encrypted data " + string(eComm[:]))
	log.Println(eComm[:])
	test := []byte{
		75, 171, 179, 168, 150, 13, 169, 80, 26, 131, 139, 152, 174, 42, 69, 237, 56, 148, 43, 29, 48, 179, 116, 109, 226, 86, 102, 236, 225, 150, 192, 52, 96, 6, 203, 147, 106, 50, 228, 117, 89, 220, 214, 2, 156, 53, 86, 236, 73, 167, 186, 30, 27, 140, 67, 181, 65, 176, 95, 115, 189, 99, 72, 219, 88, 158, 242, 101, 78, 244, 137, 80, 150, 26, 20, 163, 190, 26, 165, 45, 82, 228, 140, 100, 116, 210, 63, 247, 103, 14, 131, 22, 172, 128, 171, 121, 13, 218, 2, 217, 119, 51, 243, 39, 22, 49, 165, 4, 204, 248, 251, 129, 190, 153, 27, 170, 56, 83, 108, 87, 56, 187, 88, 9, 119, 35, 247, 125,
	}

	msg1, err := rsa.DecryptOAEP(sha1.New(), rand.Reader, privkey, test, nil)

	log.Println(string(msg1))

	// Decrypt message
	msg, err := rsa.DecryptOAEP(sha1.New(), rand.Reader, privkey, eComm, nil)
	if err != nil {
		return false, err
	}

	// If Decrypted message euqal with original - private key is correct and user authorized

	if string(msg) == testMessage {
		return true, nil
	}

	return false, nil
}
コード例 #2
0
ファイル: crypto.go プロジェクト: Javantea/h0tb0x
// Decrypts a symmetric key encrypted to this Identity
func (this *SecretIdentity) Decrypt(ek *EncryptedKey) (key *SymmetricKey) {
	out, err := rsa.DecryptOAEP(sha256.New224(), rand.Reader, this.key, ek.impl, nil)
	if err != nil {
		panic(err)
	}
	return &SymmetricKey{key: out}
}
コード例 #3
0
ファイル: WeTubeClient.go プロジェクト: imgemp/WeTube
func ReadWebSocket(ws *websocket.Conn) []byte {
	total_bytes_bytes_encrypted := make([]byte, key_len/8)
	if _, err := ws.Read(total_bytes_bytes_encrypted); err != nil {
		log.Println("(ReadWebSocket) Read Total Bytes: ", err)
	}

	sha1hash := sha1.New()
	total_bytes_bytes, err := rsa.DecryptOAEP(sha1hash, rand.Reader, pvkey, total_bytes_bytes_encrypted, nil)
	if err != nil {
		log.Println("(ReadWebSocket) Decryption: ", err)
	}

	var total_bytes uint32
	total_bytes = binary.LittleEndian.Uint32(total_bytes_bytes)

	// fmt.Printf("OAEP decrypted [%x] to \n[%d]\n",total_bytes_bytes_encrypted, total_bytes)

	var msg_splice [][]byte
	msg := make([]byte, total_bytes/2-64)
	if _, err := ws.Read(msg); err != nil {
		log.Println("(ReadTCPSocket) Read Msg: ", err)
	}
	msg2 := make([]byte, total_bytes-total_bytes/2+64)
	if _, err := ws.Read(msg2); err != nil {
		log.Println("(ReadTCPSocket) Read Msg2: ", err)
	}
	msg_splice = append(msg_splice, msg)
	msg_splice = append(msg_splice, msg2)
	return bytes.Join(msg_splice, nil)
}
コード例 #4
0
ファイル: rsa_key.go プロジェクト: acasajus/dkeyczar
func (rk *rsaKey) Decrypt(msg []byte) ([]byte, error) {
	s, err := rsa.DecryptOAEP(sha1.New(), rand.Reader, &rk.key, msg[kzHeaderLength:], nil)
	if err != nil {
		return nil, err
	}
	return s, nil
}
コード例 #5
0
ファイル: crypto.go プロジェクト: realestate-com-au/credulous
func CredulousDecodeAES(ciphertext string, privkey *rsa.PrivateKey) (plaintext string, err error) {
	in, err := base64.StdEncoding.DecodeString(ciphertext)
	if err != nil {
		return "", err
	}

	// pull apart the layers of base64-encoded JSON
	var encrypted AESEncryption
	err = json.Unmarshal(in, &encrypted)
	if err != nil {
		return "", err
	}

	encryptedKey, err := base64.StdEncoding.DecodeString(encrypted.EncodedKey)
	if err != nil {
		return "", err
	}

	// decrypt the AES key using the ssh private key
	aesKey, err := rsa.DecryptOAEP(sha1.New(), rand.Reader, privkey, encryptedKey, []byte("Credulous"))
	if err != nil {
		return "", err
	}

	plaintext, err = decodeAES(aesKey, encrypted.Ciphertext)

	return plaintext, nil
}
コード例 #6
0
ファイル: sshbox.go プロジェクト: postfix/sshbox
func decryptRSA(in, out string, key *rsa.PrivateKey, verifykey string, armour bool) (err error) {
	pkg, err := ioutil.ReadFile(in)
	if err != nil {
		fmt.Println("[!]", err.Error())
		return
	}

	lockedKey, box, err := unpackageBox(pkg)
	if err != nil {
		return
	}

	hash := sha256.New()
	boxKey, err := rsa.DecryptOAEP(hash, rand.Reader, key, lockedKey, nil)
	if err != nil {
		fmt.Println("[!] RSA decryption failed:", err.Error())
		return
	}

	message, ok := secretbox.Open(box, boxKey)
	if !ok {
		fmt.Println("[!] failed to open box.")
		err = fmt.Errorf("opening box failed")
		return
	}
	err = ioutil.WriteFile(out, message, 0644)
	return
}
コード例 #7
0
ファイル: rsautil.go プロジェクト: VukDukic/gotilla
func (enc *CryptorOAEP) DecryptOAEP(ciphertextBytes []byte, label []byte) ([]byte, error) {
	if enc.RsaPrivateKey == nil {
		err := errors.New("401: RSA Private Key Not Set")
		return []byte{}, err
	}
	return rsa.DecryptOAEP(enc.Hash, rand.Reader, enc.RsaPrivateKey, ciphertextBytes, label)
}
コード例 #8
0
ファイル: x509.go プロジェクト: leepro/goplay
func main() {
	privateKey, err := rsa.GenerateKey(rand.Reader, 512)
	if err != nil {
		fmt.Printf("rsa.GenerateKey: %v\n", err)
	}

	message := "Hello World!"
	messageBytes := bytes.NewBufferString(message)
	sha1 := sha1.New()

	encrypted, err := rsa.EncryptOAEP(sha1, rand.Reader, &privateKey.PublicKey, messageBytes.Bytes(), nil)
	if err != nil {
		fmt.Printf("EncryptOAEP: %s\n", err)
	}

	decrypted, err := rsa.DecryptOAEP(sha1, rand.Reader, privateKey, encrypted, nil)
	if err != nil {
		fmt.Printf("decrypt: %s\n", err)
	}

	decryptedString := bytes.NewBuffer(decrypted).String()
	fmt.Printf("message: %v\n", message)
	fmt.Printf("encrypted: %v\n", encrypted)
	fmt.Printf("decryptedString: %v\n", decryptedString)
}
コード例 #9
0
func decodePassword(privatekeyfile string, in string) string {
	pemData, err := ioutil.ReadFile(privatekeyfile)
	block, _ := pem.Decode(pemData)
	if block == nil {
		fmt.Errorf("bad key data: %s", "not PEM-encoded")
	}
	if got, want := block.Type, "RSA PRIVATE KEY"; got != want {
		fmt.Errorf("unknown key type %q, want %q", got, want)
	}
	priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)

	if err != nil {
		fmt.Errorf("bad private key: %s", err)
	}
	//encrypt
	//out, err := rsa.EncryptOAEP(sha1.New(), rand.Reader, &priv.PublicKey, []byte(in), []byte("aaa"))
	//if err != nil {
	//	fmt.Errorf("encrypt: %s", err)
	//}
	//encodedStr := base64.StdEncoding.EncodeToString(out)
	//fmt.Printf("encoded: %s \n", encodedStr)

	// Decrypt the data
	encodedBytes, _ := base64.StdEncoding.DecodeString(in)
	out, err := rsa.DecryptOAEP(sha1.New(), rand.Reader, priv, encodedBytes, []byte("aaa"))
	if err != nil {
		fmt.Errorf("decrypt: %s", err)
	}
	outStr := base64.StdEncoding.EncodeToString(out)
	fmt.Printf("decoded result %s\n", outStr)
	return outStr
}
コード例 #10
0
ファイル: support_test.go プロジェクト: tmroeder/cloudproxy
func TestPad(t *testing.T) {
	private, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil || private == nil {
		t.Fatal("Can't gen private key %s\n", err)
	}
	public := &private.PublicKey
	var a [9]byte
	copy(a[0:8], "IDENTITY")

	seed := []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}
	encrypted_secret, err := rsa.EncryptOAEP(sha1.New(), rand.Reader,
		public, seed, a[0:9])
	if err != nil {
		t.Fatal("Can't encrypt ", err)
	}
	fmt.Printf("encrypted_secret: %x\n", encrypted_secret)
	decrypted_secret, err := rsa.DecryptOAEP(sha1.New(), rand.Reader,
		private, encrypted_secret, a[0:9])
	if err != nil {
		t.Fatal("Can't decrypt ", err)
	}
	fmt.Printf("decrypted_secret: %x\n", decrypted_secret)
	var N *big.Int
	var D *big.Int
	var x *big.Int
	var z *big.Int
	N = public.N
	D = private.D
	x = new(big.Int)
	z = new(big.Int)
	x.SetBytes(encrypted_secret)
	z = z.Exp(x, D, N)
	decrypted_pad := z.Bytes()
	fmt.Printf("decrypted_pad   : %x\n", decrypted_pad)
}
コード例 #11
0
ファイル: rsa.go プロジェクト: codeship/go-encrypt
func (t *rsaTransformer) Decrypt(value []byte) ([]byte, error) {
	decodedValueObj, err := DecodeString(string(value))
	if err != nil {
		return nil, err
	}
	return rsa.DecryptOAEP(sha512.New(), rand.Reader, t.rsaPrivateKey, []byte(decodedValueObj), nil)
}
コード例 #12
0
ファイル: rsa_oaep.go プロジェクト: useidel/notary
func (alg *RsaOaep) Unwrap(encryptedCek []byte, key interface{}, cekSizeBits int, header map[string]interface{}) (cek []byte, err error) {
	if privKey, ok := key.(*rsa.PrivateKey); ok {
		return rsa.DecryptOAEP(alg.sha(), rand.Reader, privKey, encryptedCek, nil)
	}

	return nil, errors.New("RsaOaep.Unwrap(): expected key to be '*rsa.PrivateKey'")
}
コード例 #13
0
ファイル: rsa.go プロジェクト: rrudduck/golang-stuff
func Decrypt() {
    key := Key()
    h, ha := HashAlgorithm()
    encrypted, err := ioutil.ReadFile(EncryptedFile)
    if err != nil {
        log.Fatalf("failed reading encrypted data: %s", err)
    }

    signature, err := ioutil.ReadFile(SignatureFile)
    if err != nil {
        log.Fatalf("failed saving signature data: %s", err)
    }

    if err = rsa.VerifyPKCS1v15(&key.PublicKey, ha, HashMessage(encrypted), signature); err != nil {
        log.Fatalf("message not valid: %s", err)
    } else {
        log.Printf("message is valid!")
    }

    plaintext, err := rsa.DecryptOAEP(h, rand.Reader, key, encrypted, nil)
    if err != nil {
        log.Fatalf("failed decrypting: %s", err)
    }
    log.Printf("decrypted message: %s", plaintext)
}
コード例 #14
0
// Decrypt the Hello using the node's private comms key, and decode its
// contents.
func ServerDecryptHello(ciphertext []byte, ckPriv *rsa.PrivateKey, rng *xr.PRNG) (
	sOneShot *AesSession, version1s uint32, err error) {
	if rng == nil {
		rng = xr.MakeSystemRNG()
	}
	sha := sha1.New()
	data, err := rsa.DecryptOAEP(sha, nil, ckPriv, ciphertext, nil)
	// DEBUG
	if err == nil {
		expectedLen := 2*aes.BlockSize + 12
		if len(data) != expectedLen {
			fmt.Printf("expected OAEP packet len %d, actual %d bytes\n",
				expectedLen, len(data))
			err = WrongOAEPSize // XXX BAD NAME
		}
	}
	// END
	if err == nil {
		key1s := data[:2*aes.BlockSize]
		// salt1s = data[2*aes.BlockSize : 2*aes.BlockSize+8]
		vBytes := data[2*aes.BlockSize+8:]
		version1s = uint32(vBytes[0]) |
			uint32(vBytes[1])<<8 |
			uint32(vBytes[2])<<16 |
			uint32(vBytes[3])<<24
		sOneShot, err = NewAesSession(key1s, rng)
	}
	return
}
コード例 #15
0
ファイル: auth.go プロジェクト: frodosens/go-airplay
// Takes the rsaaeskey message (in the ANNOUNCE body) and decrypts it to an
// aes key.
func aeskeyFromRsa(rsaaeskey64 string) (key []byte, err error) {
	s64 := base64pad(rsaaeskey64)
	s, err := base64.StdEncoding.DecodeString(s64)
	if err != nil {
		return
	}
	return rsa.DecryptOAEP(sha1.New(), nil, rsaPrivKey, s, nil)
}
コード例 #16
0
ファイル: encryption.go プロジェクト: postfix/secureBox
// decrypts a given message with the provided RSA private key
// the label must be the same for the encryption and decryption for it to work.
func decryptRSA(private *rsa.PrivateKey, ciphertext []byte) []byte {
	label := make([]byte, 10)
	message, err := rsa.DecryptOAEP(sha512.New(), rand.Reader, private, ciphertext, label)
	if err != nil {
		fmt.Println("decryption failed!: ", err)
	}
	return message
}
コード例 #17
0
ファイル: asymmetric.go プロジェクト: ossrs/go-oryx-lib
// Decrypt the given payload. Based on the key encryption algorithm,
// this will either use RSA-PKCS1v1.5 or RSA-OAEP (with SHA-1 or SHA-256).
func (ctx rsaDecrypterSigner) decrypt(jek []byte, alg KeyAlgorithm, generator keyGenerator) ([]byte, error) {
	// Note: The random reader on decrypt operations is only used for blinding,
	// so stubbing is meanlingless (hence the direct use of rand.Reader).
	switch alg {
	case RSA1_5:
		defer func() {
			// DecryptPKCS1v15SessionKey sometimes panics on an invalid payload
			// because of an index out of bounds error, which we want to ignore.
			// This has been fixed in Go 1.3.1 (released 2014/08/13), the recover()
			// only exists for preventing crashes with unpatched versions.
			// See: https://groups.google.com/forum/#!topic/golang-dev/7ihX6Y6kx9k
			// See: https://code.google.com/p/go/source/detail?r=58ee390ff31602edb66af41ed10901ec95904d33
			_ = recover()
		}()

		// Perform some input validation.
		keyBytes := ctx.privateKey.PublicKey.N.BitLen() / 8
		if keyBytes != len(jek) {
			// Input size is incorrect, the encrypted payload should always match
			// the size of the public modulus (e.g. using a 2048 bit key will
			// produce 256 bytes of output). Reject this since it's invalid input.
			return nil, ErrCryptoFailure
		}

		cek, _, err := generator.genKey()
		if err != nil {
			return nil, ErrCryptoFailure
		}

		// When decrypting an RSA-PKCS1v1.5 payload, we must take precautions to
		// prevent chosen-ciphertext attacks as described in RFC 3218, "Preventing
		// the Million Message Attack on Cryptographic Message Syntax". We are
		// therefore deliberately ignoring errors here.
		_ = rsa.DecryptPKCS1v15SessionKey(rand.Reader, ctx.privateKey, jek, cek)

		return cek, nil
	case RSA_OAEP:
		// Use rand.Reader for RSA blinding
		return rsa.DecryptOAEP(sha1.New(), rand.Reader, ctx.privateKey, jek, []byte{})
	case RSA_OAEP_256:
		// Use rand.Reader for RSA blinding
		return rsa.DecryptOAEP(sha256.New(), rand.Reader, ctx.privateKey, jek, []byte{})
	}

	return nil, ErrUnsupportedAlgorithm
}
コード例 #18
0
func DecryptWithPrivateKey(recipientPvtKey *rsa.PrivateKey, cipher []byte) ([]byte, error) {
	sha_hash := sha256.New()

	decrypted, err := rsa.DecryptOAEP(sha_hash, rand.Reader, recipientPvtKey, cipher, label)
	if err != nil {
		return nil, err
	}

	return decrypted, nil
}
コード例 #19
0
ファイル: cryptography.go プロジェクト: rakhra/launchkey-go
func DecryptMessage(message string, privateKey *rsa.PrivateKey) []byte {
	decodedMessage := base64Decode(message)
	decryptedMessage, err := rsa.DecryptOAEP(sha1.New(), rand.Reader, privateKey, []byte(decodedMessage), nil)

	if err != nil {
		return nil
	}

	return decryptedMessage
}
コード例 #20
0
ファイル: cryp.go プロジェクト: weimingtom/tank_battle
func (ct *CryptoTool) Dec(in []byte) []byte {
	if ct.privateKey == nil {
		log.Fatalln("No private key?!")
	}
	out, err := rsa.DecryptOAEP(ct.sha1, rand.Reader, ct.privateKey, in, nil)
	if err != nil {
		log.Fatalln("DecryptOAEP fail", err)
	}
	return out
}
コード例 #21
0
func Decrypt_oaep(private_key *rsa.PrivateKey, encrypted, label []byte) (decrypted []byte) {
	var err error
	var md5_hash hash.Hash

	md5_hash = md5.New()
	if decrypted, err = rsa.DecryptOAEP(md5_hash, rand.Reader, private_key, encrypted, label); err != nil {
		log.Fatal(err)
	}
	return
}
コード例 #22
0
ファイル: rosa.go プロジェクト: MrGosti/rosa
//Decrypt decrypt the given message with the given private key.
func Decrypt(content []byte, privatekey *rsa.PrivateKey) ([]byte, error) {
	md5hash := md5.New()
	label := []byte("")

	decryptedmsg, err := rsa.DecryptOAEP(md5hash, rand.Reader, privatekey, content, label)

	if err != nil {
		return nil, err
	}
	return decryptedmsg, nil
}
コード例 #23
0
ファイル: cryptor.go プロジェクト: zhoudianyou/goim
func (c *DefaultCryptor) Exchange(pri *rsa.PrivateKey, cipherText []byte) (ki []byte, err error) {
	if ki, err = rsa.DecryptOAEP(sha256.New(), nil, pri, cipherText, nil); err != nil {
		log.Error("rsa.DecryptOAEP() error(%v)", err)
		return
	}
	if len(ki) != c.dataLen {
		log.Warn("handshake aes key size not valid: %d", len(ki))
		err = ErrHandshake
	}
	return
}
コード例 #24
0
// Decrypt decrypts a given EncryptedMessage using the provided private key.
// If the provided key is invalid then Decrypt will return an empty slice and an error.
// Decrypt does not validate the authenticity of the encrypted message.
func Decrypt(privateKey *rsa.PrivateKey, msg EncryptedMessage) ([]byte, error) {
	if privateKey == nil {
		return []byte{}, errors.New("private key must not be nil")
	}

	aesKey, err := rsa.DecryptOAEP(sha256.New(), rand.Reader, privateKey, msg.EncryptedKey, nil)
	if err != nil {
		return []byte{}, err
	}

	return symmetricDecrypt(aesKey, msg.Ciphertext)
}
コード例 #25
0
ファイル: rsaexample.go プロジェクト: wujunjian/go
func main() {
	flag.Parse()

	// Read the input file
	in, err := ioutil.ReadFile(*inFile)
	if err != nil {
		log.Fatalf("input file: %s", err)
	}
	fmt.Println(len(in), in)

	// Read the private key
	pemData, err := ioutil.ReadFile(*keyFile)
	if err != nil {
		log.Fatalf("read key file: %s", err)
	}

	// Extract the PEM-encoded data block
	block, _ := pem.Decode(pemData)
	if block == nil {
		log.Fatalf("bad key data: %s", "not PEM-encoded")
	}
	if got, want := block.Type, "RSA PRIVATE KEY"; got != want {
		log.Fatalf("unknown key type %q, want %q", got, want)
	}

	// Decode the RSA private key
	priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
	if err != nil {
		log.Fatalf("bad private key: %s", err)
	}

	label := []byte("orders")
	var out []byte
	if *decrypt {
		// Decrypt the data
		out, err = rsa.DecryptOAEP(sha256.New(), rand.Reader, priv, in, label)
		if err != nil {
			log.Fatalf("decrypt: %s", err)
		}
	} else {
		out, err = rsa.EncryptOAEP(sha256.New(), rand.Reader, &priv.PublicKey, in, label)
		if err != nil {
			log.Fatalf("encrypt: %s", err)
		}
		//fmt.Println(priv.PublicKey)
		//fmt.Println(priv)
	}

	// Write data to output file
	if err := ioutil.WriteFile(*outFile, out, 0600); err != nil {
		log.Fatalf("write output: %s", err)
	}
}
コード例 #26
0
ファイル: crypto.go プロジェクト: realestate-com-au/credulous
func CredulousDecodeWithSalt(ciphertext string, salt string, privkey *rsa.PrivateKey) (plaintext string, err error) {
	in, err := base64.StdEncoding.DecodeString(ciphertext)
	if err != nil {
		return "", err
	}
	out, err := rsa.DecryptOAEP(sha1.New(), rand.Reader, privkey, in, []byte("Credulous"))
	if err != nil {
		return "", err
	}
	plaintext = strings.Replace(string(out), salt, "", 1)
	return plaintext, nil
}
コード例 #27
0
ファイル: key_encrypt.go プロジェクト: nabeken/go-jwx
func (d RSAOAEPKeyDecrypt) KeyDecrypt(enckey []byte) ([]byte, error) {
	debug.Printf("START OAEP.KeyDecrypt")
	var hash hash.Hash
	switch d.alg {
	case jwa.RSA_OAEP:
		hash = sha1.New()
	case jwa.RSA_OAEP_256:
		hash = sha256.New()
	default:
		return nil, errors.New("failed to generate key encrypter for RSA-OAEP: RSA_OAEP/RSA_OAEP_256 required")
	}
	return rsa.DecryptOAEP(hash, rand.Reader, d.privkey, enckey, []byte{})
}
コード例 #28
0
ファイル: rsa.go プロジェクト: releasifier/releasifier
func (r *RSA) Decrypt(data []byte) ([]byte, error) {
	var sha1Hash hash.Hash
	var label []byte

	sha1Hash = sha1.New()

	decrypted, err := rsa.DecryptOAEP(sha1Hash, rand.Reader, r.privateKey, data, label)
	if err != nil {
		return nil, err
	}

	return decrypted, nil
}
コード例 #29
0
ファイル: store.go プロジェクト: ibmendoza/dgtk
func (store *Store) Get(key string, login string, secret string) (b []byte, e error) {
	privateKey := &rsa.PrivateKey{}
	raw, e := ioutil.ReadFile(store.userPath(login) + "/id_rsa")
	if e != nil {
		return nil, e
	}
	decoded, e := b64.DecodeString(string(raw))
	if e != nil {
		return nil, e
	}
	hashedPassword := hashPassword(secret)
	crypter := newCrypter(hashedPassword)
	decrypted, e := crypter.Decrypt(decoded)
	if e != nil {
		return nil, e
	}
	e = json.Unmarshal([]byte(decrypted), privateKey)
	if e != nil {
		return nil, e
	}

	dir := store.storePath(login) + "/" + key
	secretKey, e := ioutil.ReadFile(dir + "/BLOB.key")
	if e != nil {
		return nil, e
	}
	decodedSecretKey, e := b64.DecodeString(string(secretKey))
	if e != nil {
		return nil, e
	}

	s, e := rsa.DecryptOAEP(sha1.New(), rand.Reader, privateKey, decodedSecretKey, nil)
	if e != nil {
		return nil, e
	}

	blob, e := ioutil.ReadFile(dir + "/BLOB")
	if e != nil {
		return nil, e
	}
	decodedBlob, e := b64.DecodeString(string(blob))
	if e != nil {
		return nil, e
	}
	crypter = newCrypter(s)
	decryptedDecodedBlob, e := crypter.Decrypt(decodedBlob)
	if e != nil {
		return nil, e
	}
	return []byte(decryptedDecodedBlob), nil
}
コード例 #30
0
//SymmetricKey returns the private key contained in the EncryptedKey document
func (ek *EncryptedKey) SymmetricKey(cert tls.Certificate) (cipher.Block, error) {

	encCert, err := xmlBytes(ek.X509Data)
	if err != nil {
		return nil, fmt.Errorf("error getting certificate from encryptedkey: %v", err)
	}

	if len(cert.Certificate) < 1 {
		return nil, fmt.Errorf("decryption tls.Certificate has no public certs attached")
	}

	if !bytes.Equal(cert.Certificate[0], encCert) {
		return nil, fmt.Errorf("key decryption attempted with mismatched cert")
	}

	cipherText, err := xmlBytes(ek.CipherValue)
	if err != nil {
		return nil, err
	}

	switch pk := cert.PrivateKey.(type) {
	case *rsa.PrivateKey:
		var h hash.Hash

		switch ek.EncryptionMethod.DigestMethod.Algorithm {
		case MethodSHA1:
			h = sha1.New()
		case MethodSHA256:
			h = sha256.New()
		}

		switch ek.EncryptionMethod.Algorithm {
		case MethodRSAOAEP:
			pt, err := rsa.DecryptOAEP(h, rand.Reader, pk, cipherText, nil)
			if err != nil {
				return nil, fmt.Errorf("rsa internal error: %v", err)
			}

			b, err := aes.NewCipher(pt)
			if err != nil {
				return nil, err
			}

			return b, nil
		default:
			return nil, fmt.Errorf("unsupported encryption algorithm: %s", ek.EncryptionMethod.Algorithm)
		}
	}
	return nil, fmt.Errorf("no cipher for decoding symmetric key")
}