public static BigInteger Transform(string name, bool encrypt, BigInteger key, BigInteger message) { using (var cipher = SymmetricAlgorithm.Create(name)) { // Bug - https://github.com/sgbj/Dukpt.NET/issues/5 - Specified key is not a valid size for this algorithm. // I usually trim the zero-bytes off the front of the array in the GetBytes method, // but this algorithm expects either 8 or 16 byte keys, so GetBytes will occasionally return 7. var k = key.GetBytes(); cipher.Key = new byte[Math.Max(0, 8 - k.Length)].Concat(key.GetBytes()).ToArray(); cipher.IV = new byte[8]; cipher.Mode = CipherMode.CBC; cipher.Padding = PaddingMode.Zeros; using (var crypto = encrypt ? cipher.CreateEncryptor() : cipher.CreateDecryptor()) { var data = message.GetBytes(); return BigInt.FromBytes(crypto.TransformFinalBlock(data, 0, data.Length)); } } }
public static BigInteger Transform(string name, bool encrypt, BigInteger key, BigInteger message) { using (var cipher = SymmetricAlgorithm.Create(name)) { var k = key.GetBytes(); //Credit goes to ichoes (https://github.com/ichoes) for fixing this issue (https://github.com/sgbj/Dukpt.NET/issues/5) //gets the next multiple of 8 cipher.Key = new byte[Math.Max(0, GetNearestWholeMultiple(k.Length, 8) - k.Length)].Concat(key.GetBytes()).ToArray(); cipher.IV = new byte[8]; cipher.Mode = CipherMode.CBC; cipher.Padding = PaddingMode.Zeros; using (var crypto = encrypt ? cipher.CreateEncryptor() : cipher.CreateDecryptor()) { var data = message.GetBytes(); //Added the GetNearestWholeMultiple here. data = new byte[Math.Max(0, GetNearestWholeMultiple(data.Length, 8) - data.Length)].Concat(message.GetBytes()).ToArray(); return BigInt.FromBytes(crypto.TransformFinalBlock(data, 0, data.Length)); } } }
public void WriteBigInt(BigInteger b, int length) { byte[] bytes = b.GetBytes(); int bytes_copy_amount = Math.Min(length, bytes.Length); Write(bytes, 0, bytes_copy_amount); for (int i = bytes.Length; i < length; ++i) Write((byte) 0); //pad }