package rfc3961

// Implementation of the n-fold algorithm as defined in RFC 3961.

/* Credits
This golang implementation of nfold used the following project for help with implementation detail.
Although their source is in java it was helpful as a reference implementation of the RFC.
You can find the source code of their open source project along with license information below.
We acknowledge and are grateful to these developers for their contributions to open source

Project: Apache Directory (http://http://directory.apache.org/)
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
License: http://www.apache.org/licenses/LICENSE-2.0
*/

// Nfold expands the key to ensure it is not smaller than one cipher block.
// Defined in RFC 3961.
//
// m input bytes that will be "stretched" to the least common multiple of n bits and the bit length of m.
func ( []byte,  int) []byte {
	 := len() * 8

	//Get the lowest common multiple of the two bit sizes
	 := lcm(, )
	 :=  / 
	var  []byte

	for  := 0;  < ; ++ {
		 := 13 * 
		 = append(, rotateRight(, )...)
	}

	 := make([]byte, /8)
	 := make([]byte, /8)
	for  := 0;  < /; ++ {
		for  := 0;  < /8; ++ {
			[] = [+(*len())]
		}
		 = onesComplementAddition(, )
	}
	return 
}

func onesComplementAddition(,  []byte) []byte {
	 := len() * 8
	 := make([]byte, /8)
	 := 0
	for  :=  - 1;  > -1; -- {
		 := getBit(&, )
		 := getBit(&, )
		 :=  +  + 

		if  == 0 ||  == 1 {
			setBit(&, , )
			 = 0
		} else if  == 2 {
			 = 1
		} else if  == 3 {
			setBit(&, , 1)
			 = 1
		}
	}
	if  == 1 {
		 := make([]byte, len())
		[len()-1] = 1
		 = (, )
	}
	return 
}

func rotateRight( []byte,  int) []byte {
	 := make([]byte, len())
	 := len() * 8
	for  := 0;  < ; ++ {
		 := getBit(&, )
		setBit(&, (+)%, )
	}
	return 
}

func lcm(,  int) int {
	return ( * ) / gcd(, )
}

func gcd(,  int) int {
	for  != 0 {
		,  = , %
	}
	return 
}

func getBit( *[]byte,  int) int {
	 :=  / 8
	 := uint( % 8)
	 := (*)[]
	 := int( >> (8 - ( + 1)) & 0x0001)
	return 
}

func setBit( *[]byte, ,  int) {
	 :=  / 8
	 := uint( % 8)
	 := (*)[]
	var  byte
	 = byte(<<(8-(+1))) | 
	(*)[] = 
}