File: secret_key.go

package info (click to toggle)
golang-github-miekg-pkcs11 1.0.3%2Bdfsg1-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, sid
  • size: 400 kB
  • sloc: makefile: 20; ansic: 19
file content (42 lines) | stat: -rw-r--r-- 1,293 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package p11

import "github.com/miekg/pkcs11"

// SecretKey is an Object representing a secret (symmetric) key. Since any object can be cast to a
// SecretKey, it is the user's responsibility to ensure that the object is
// actually a secret key. For instance, if you use a FindObjects template that
// includes CKA_CLASS: CKO_SECRET_KEY, you can be confident the resulting object
// is a secret key.
type SecretKey Object

// Encrypt encrypts a plaintext with a given mechanism.
func (secret SecretKey) Encrypt(mechanism pkcs11.Mechanism, plaintext []byte) ([]byte, error) {
	s := secret.session
	s.Lock()
	defer s.Unlock()
	err := s.ctx.EncryptInit(s.handle, []*pkcs11.Mechanism{&mechanism}, secret.objectHandle)
	if err != nil {
		return nil, err
	}
	out, err := s.ctx.Encrypt(s.handle, plaintext)
	if err != nil {
		return nil, err
	}
	return out, nil
}

// Decrypt decrypts the input with a given mechanism.
func (secret SecretKey) Decrypt(mechanism pkcs11.Mechanism, ciphertext []byte) ([]byte, error) {
	s := secret.session
	s.Lock()
	defer s.Unlock()
	err := s.ctx.DecryptInit(s.handle, []*pkcs11.Mechanism{&mechanism}, secret.objectHandle)
	if err != nil {
		return nil, err
	}
	out, err := s.ctx.Decrypt(s.handle, ciphertext)
	if err != nil {
		return nil, err
	}
	return out, nil
}