EncryptionEngine.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. package crypto
  2. import (
  3. "bytes"
  4. "crypto/hmac"
  5. "encoding/binary"
  6. "errors"
  7. "fmt"
  8. "hash"
  9. )
  10. type EType interface {
  11. GetETypeID() int
  12. GetKeyByteSize() int // See "protocol key format" for defined values
  13. GetKeySeedBitLength() int // key-generation seed length, k
  14. GetDefaultStringToKeyParams() string // default string-to-key parameters (s2kparams)
  15. StringToKey(string, salt, s2kparams string) ([]byte, error) // string-to-key (UTF-8 string, UTF-8 string, opaque)->(protocol-key)
  16. RandomToKey(b []byte) []byte // random-to-key (bitstring[K])->(protocol-key)
  17. GetHMACBitLength() int // HMAC output size, h
  18. GetMessageBlockByteSize() int // message block size, m
  19. Encrypt(key, message []byte) ([]byte, []byte, error) // E function - encrypt (specific-key, state, octet string)->(state, octet string)
  20. Decrypt(key, ciphertext []byte) ([]byte, error) // D function
  21. GetCypherBlockBitLength() int // cipher block size, c
  22. GetConfounderByteSize() int // This is the same as the cipher block size but in bytes.
  23. DeriveKey(protocolKey, usage []byte) ([]byte, error) // DK key-derivation (protocol-key, integer)->(specific-key)
  24. DeriveRandom(protocolKey, usage []byte) ([]byte, error) // DR pseudo-random (protocol-key, octet-string)->(octet-string)
  25. VerifyChecksum(protocolKey, ct, pt []byte, usage int) bool
  26. GetHash() hash.Hash
  27. }
  28. // RFC3961: DR(Key, Constant) = k-truncate(E(Key, Constant, initial-cipher-state))
  29. // key - base key or protocol key. Likely to be a key from a keytab file
  30. // TODO usage - a constant
  31. // n - block size in bits (not bytes) - note if you use something like aes.BlockSize this is in bytes.
  32. // k - key length / key seed length in bits. Eg. for AES256 this value is 256
  33. // encrypt - the encryption function to use
  34. func deriveRandom(key, usage []byte, n, k int, e EType) ([]byte, error) {
  35. //Ensure the usage constant is at least the size of the cypher block size. Pass it through the nfold algorithm that will "stretch" it if needs be.
  36. nFoldUsage := Nfold(usage, n)
  37. //k-truncate implemented by creating a byte array the size of k (k is in bits hence /8)
  38. out := make([]byte, k/8)
  39. /*If the output of E is shorter than k bits, it is fed back into the encryption as many times as necessary.
  40. The construct is as follows (where | indicates concatentation):
  41. K1 = E(Key, n-fold(Constant), initial-cipher-state)
  42. K2 = E(Key, K1, initial-cipher-state)
  43. K3 = E(Key, K2, initial-cipher-state)
  44. K4 = ...
  45. DR(Key, Constant) = k-truncate(K1 | K2 | K3 | K4 ...)*/
  46. _, K, err := e.Encrypt(key, nFoldUsage)
  47. if err != nil {
  48. return out, err
  49. }
  50. for i := copy(out, K); i < len(out); {
  51. _, K, _ = e.Encrypt(key, K)
  52. i = i + copy(out[i:], K)
  53. }
  54. return out, nil
  55. }
  56. func zeroPad(b []byte, m int) ([]byte, error) {
  57. if m <= 0 {
  58. return nil, errors.New("Invalid message block size when padding")
  59. }
  60. if b == nil || len(b) == 0 {
  61. return nil, errors.New("Data not valid to pad: Zero size")
  62. }
  63. if l := len(b) % m; l != 0 {
  64. n := m - l
  65. z := make([]byte, n)
  66. b = append(b, z...)
  67. }
  68. return b, nil
  69. }
  70. func pkcs7Pad(b []byte, m int) ([]byte, error) {
  71. if m <= 0 {
  72. return nil, errors.New("Invalid message block size when padding")
  73. }
  74. if b == nil || len(b) == 0 {
  75. return nil, errors.New("Data not valid to pad: Zero size")
  76. }
  77. n := m - (len(b) % m)
  78. pb := make([]byte, len(b)+n)
  79. copy(pb, b)
  80. copy(pb[len(b):], bytes.Repeat([]byte{byte(n)}, n))
  81. return pb, nil
  82. }
  83. func pkcs7Unpad(b []byte, m int) ([]byte, error) {
  84. if m <= 0 {
  85. return nil, errors.New("Invalid message block size when unpadding")
  86. }
  87. if b == nil || len(b) == 0 {
  88. return nil, errors.New("Padded data not valid: Zero size")
  89. }
  90. if len(b)%m != 0 {
  91. return nil, errors.New("Padded data not valid: Not multiple of message block size")
  92. }
  93. c := b[len(b)-1]
  94. n := int(c)
  95. if n == 0 || n > len(b) {
  96. return nil, errors.New("Padded data not valid: Data may not have been padded")
  97. }
  98. for i := 0; i < n; i++ {
  99. if b[len(b)-n+i] != c {
  100. return nil, errors.New("Padded data not valid")
  101. }
  102. }
  103. return b[:len(b)-n], nil
  104. }
  105. func GetChecksum(pt, key []byte, usage int, etype EType) ([]byte, error) {
  106. k, err := etype.DeriveKey(key, GetUsageKi(uint32(usage)))
  107. if err != nil {
  108. return nil, fmt.Errorf("Unable to derive key for checksum: %v", err)
  109. }
  110. mac := hmac.New(etype.GetHash, k)
  111. mac.Write(pt)
  112. return mac.Sum(nil), nil
  113. }
  114. func VerifyChecksum(key, ct, pt []byte, usage int, etype EType) bool {
  115. //The ciphertext output is the concatenation of the output of the basic
  116. //encryption function E and a (possibly truncated) HMAC using the
  117. //specified hash function H, both applied to the plaintext with a
  118. //random confounder prefix and sufficient padding to bring it to a
  119. //multiple of the message block size. When the HMAC is computed, the
  120. //key is used in the protocol key form.
  121. // HMAC(Ki, P1)[1..h] - note this starts from 1 not zero hence getting the last etype.GetHMACBitLength()/8 + 1 bytes not 12 and [1:12]
  122. h := ct[len(ct)-etype.GetHMACBitLength()/8+1:]
  123. expectedMAC, _ := GetChecksum(pt, key, usage, etype)
  124. return hmac.Equal(h, expectedMAC[1:etype.GetHMACBitLength()/8])
  125. }
  126. /*
  127. Key Usage Numbers
  128. RFC 3961: The "well-known constant" used for the DK function is the key usage number, expressed as four octets in big-endian order, followed by one octet indicated below.
  129. Kc = DK(base-key, usage | 0x99);
  130. Ke = DK(base-key, usage | 0xAA);
  131. Ki = DK(base-key, usage | 0x55);
  132. */
  133. // un - usage number
  134. func GetUsageKc(un uint32) []byte {
  135. return getUsage(un, 0x99)
  136. }
  137. // un - usage number
  138. func GetUsageKe(un uint32) []byte {
  139. return getUsage(un, 0xAA)
  140. }
  141. // un - usage number
  142. func GetUsageKi(un uint32) []byte {
  143. return getUsage(un, 0x55)
  144. }
  145. func getUsage(un uint32, o byte) []byte {
  146. var buf bytes.Buffer
  147. binary.Write(&buf, binary.BigEndian, un)
  148. return append(buf.Bytes(), o)
  149. }
  150. var KeyUsageNumbers map[int]string = map[int]string{
  151. 1: "AS-REQ PA-ENC-TIMESTAMP padata timestamp, encrypted with the client key",
  152. 2: "AS-REP Ticket and TGS-REP Ticket (includes TGS session key or application session key), encrypted with the service key",
  153. 3: "AS-REP encrypted part (includes TGS session key or application session key), encrypted with the client key",
  154. 4: "TGS-REQ KDC-REQ-BODY AuthorizationData, encrypted with the TGS session key",
  155. 5: "TGS-REQ KDC-REQ-BODY AuthorizationData, encrypted with the TGS authenticator subkey",
  156. 6: "TGS-REQ PA-TGS-REQ padata AP-REQ Authenticator cksum, keyed with the TGS session key",
  157. 7: "TGS-REQ PA-TGS-REQ padata AP-REQ Authenticator (includes TGS authenticator subkey), encrypted with the TGS session key",
  158. 8: "TGS-REP encrypted part (includes application session key), encrypted with the TGS session key",
  159. 9: "TGS-REP encrypted part (includes application session key), encrypted with the TGS authenticator subkey",
  160. 10: "AP-REQ Authenticator cksum, keyed with the application session key",
  161. 11: "AP-REQ Authenticator (includes application authenticator subkey), encrypted with the application session key",
  162. 12: "AP-REP encrypted part (includes application session subkey), encrypted with the application session key",
  163. 13: "KRB-PRIV encrypted part, encrypted with a key chosen by the application",
  164. 14: "KRB-CRED encrypted part, encrypted with a key chosen by the application",
  165. 15: "KRB-SAFE cksum, keyed with a key chosen by the application",
  166. 19: "AD-KDC-ISSUED checksum",
  167. 1024: "Encryption for application use in protocols that do not specify key usage values",
  168. }