Debian Codegraph @

crypto/rfc3961/nfold.go

raw symbols SCIP
1 package rfc3961
2
3 /* Credits
4 This golang implementation of nfold used the following project for help with implementation detail.
5 Although their source is in java it was helpful as a reference implementation of the RFC.
6 You can find the source code of their open source project along with license information below.
7 We acknowledge and are grateful to these developers for their contributions to open source
8
9 Project: Apache Directory (http://http://directory.apache.org/)
10 https://svn.apache.org/repos/asf/directory/apacheds/tags/1.5.1/kerberos-shared/src/main/java/org/apache/directory/server/kerberos/shared/crypto/encryption/NFold.java
11 License: http://www.apache.org/licenses/LICENSE-2.0
12 */
13
14 // Nfold expands the key to ensure it is not smaller than one cipher block.
15 // Defined in RFC 3961.
16 //
17 // m input bytes that will be "stretched" to the least common multiple of n bits and the bit length of m.
18 func Nfold(m []byte, n int) []byte {
19 k := len(m) * 8
20
21 //Get the lowest common multiple of the two bit sizes
22 lcm := lcm(n, k)
23 relicate := lcm / k
24 var sumBytes []byte
25
26 for i := 0; i < relicate; i++ {
27 rotation := 13 * i
28 sumBytes = append(sumBytes, rotateRight(m, rotation)...)
29 }
30
31 nfold := make([]byte, n/8)
32 sum := make([]byte, n/8)
33 for i := 0; i < lcm/n; i++ {
34 for j := 0; j < n/8; j++ {
35 sum[j] = sumBytes[j+(i*len(sum))]
36 }
37 nfold = onesComplementAddition(nfold, sum)
38 }
39 return nfold
40 }
41
42 func onesComplementAddition(n1, n2 []byte) []byte {
43 numBits := len(n1) * 8
44 out := make([]byte, numBits/8)
45 carry := 0
46 for i := numBits - 1; i > -1; i-- {
47 n1b := getBit(&n1, i)
48 n2b := getBit(&n2, i)
49 s := n1b + n2b + carry
50
51 if s == 0 || s == 1 {
52 setBit(&out, i, s)
53 carry = 0
54 } else if s == 2 {
55 carry = 1
56 } else if s == 3 {
57 setBit(&out, i, 1)
58 carry = 1
59 }
60 }
61 if carry == 1 {
62 carryArray := make([]byte, len(n1))
63 carryArray[len(carryArray)-1] = 1
64 out = onesComplementAddition(out, carryArray)
65 }
66 return out
67 }
68
69 func rotateRight(b []byte, step int) []byte {
70 out := make([]byte, len(b))
71 bitLen := len(b) * 8
72 for i := 0; i < bitLen; i++ {
73 v := getBit(&b, i)
74 setBit(&out, (i+step)%bitLen, v)
75 }
76 return out
77 }
78
79 func lcm(x, y int) int {
80 return (x * y) / gcd(x, y)
81 }
82
83 func gcd(x, y int) int {
84 for y != 0 {
85 x, y = y, x%y
86 }
87 return x
88 }
89
90 func getBit(b *[]byte, p int) int {
91 pByte := p / 8
92 pBit := uint(p % 8)
93 vByte := (*b)[pByte]
94 vInt := int(vByte >> (8 - (pBit + 1)) & 0x0001)
95 return vInt
96 }
97
98 func setBit(b *[]byte, p, v int) {
99 pByte := p / 8
100 pBit := uint(p % 8)
101 oldByte := (*b)[pByte]
102 var newByte byte
103 newByte = byte(v<<(8-(pBit+1))) | oldByte
104 (*b)[pByte] = newByte
105 }