EncryptionEngine.go 6.4 KB

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