Cryptosystem.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package types
  2. import (
  3. "crypto/rand"
  4. "github.com/jcmturner/gofork/encoding/asn1"
  5. "github.com/jcmturner/gokrb5/v8/crypto/etype"
  6. )
  7. // Reference: https://www.ietf.org/rfc/rfc4120.txt
  8. // Section: 5.2.9
  9. // EncryptedData implements RFC 4120 type: https://tools.ietf.org/html/rfc4120#section-5.2.9
  10. type EncryptedData struct {
  11. EType int32 `asn1:"explicit,tag:0"`
  12. KVNO int `asn1:"explicit,optional,tag:1"`
  13. Cipher []byte `asn1:"explicit,tag:2"`
  14. }
  15. // EncryptionKey implements RFC 4120 type: https://tools.ietf.org/html/rfc4120#section-5.2.9
  16. // AKA KeyBlock
  17. type EncryptionKey struct {
  18. KeyType int32 `asn1:"explicit,tag:0"`
  19. KeyValue []byte `asn1:"explicit,tag:1" json:"-"`
  20. }
  21. // Checksum implements RFC 4120 type: https://tools.ietf.org/html/rfc4120#section-5.2.9
  22. type Checksum struct {
  23. CksumType int32 `asn1:"explicit,tag:0"`
  24. Checksum []byte `asn1:"explicit,tag:1"`
  25. }
  26. // Unmarshal bytes into the EncryptedData.
  27. func (a *EncryptedData) Unmarshal(b []byte) error {
  28. _, err := asn1.Unmarshal(b, a)
  29. return err
  30. }
  31. // Marshal the EncryptedData.
  32. func (a *EncryptedData) Marshal() ([]byte, error) {
  33. edb, err := asn1.Marshal(*a)
  34. if err != nil {
  35. return edb, err
  36. }
  37. return edb, nil
  38. }
  39. // Unmarshal bytes into the EncryptionKey.
  40. func (a *EncryptionKey) Unmarshal(b []byte) error {
  41. _, err := asn1.Unmarshal(b, a)
  42. return err
  43. }
  44. // Unmarshal bytes into the Checksum.
  45. func (a *Checksum) Unmarshal(b []byte) error {
  46. _, err := asn1.Unmarshal(b, a)
  47. return err
  48. }
  49. // GenerateEncryptionKey creates a new EncryptionKey with a random key value.
  50. func GenerateEncryptionKey(etype etype.EType) (EncryptionKey, error) {
  51. k := EncryptionKey{
  52. KeyType: etype.GetETypeID(),
  53. }
  54. b := make([]byte, etype.GetKeyByteSize(), etype.GetKeyByteSize())
  55. _, err := rand.Read(b)
  56. if err != nil {
  57. return k, err
  58. }
  59. k.KeyValue = b
  60. return k, nil
  61. }