summary refs log tree commit diff
path: root/crypto/src/util/ssh/SSHBuilder.cs
blob: 24121d0d8325349eb05f7c01b61cc0e69ef50da1 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
using System;
using System.IO;

using Org.BouncyCastle.Math;

namespace Org.BouncyCastle.Utilities.SSH
{
    internal class SshBuilder
    {
        private readonly MemoryStream bos = new MemoryStream();

        public void U32(uint value)
        {
            bos.WriteByte(Convert.ToByte((value >> 24) & 0xFF));
            bos.WriteByte(Convert.ToByte((value >> 16) & 0xFF));
            bos.WriteByte(Convert.ToByte((value >> 8) & 0xFF));
            bos.WriteByte(Convert.ToByte(value & 0xFF));
        }

        public void WriteBigNum(BigInteger n)
        {
            WriteBlock(n.ToByteArray());
        }

        public void WriteBlock(byte[] value)
        {
            U32((uint)value.Length);
            try
            {
                bos.Write(value, 0, value.Length);
            }
            catch (IOException e)
            {
                throw new InvalidOperationException(e.Message, e);
            }
        }

        public void WriteBytes(byte[] value)
        {
            try
            {
                bos.Write(value, 0, value.Length);
            }
            catch (IOException e)
            {
                throw new InvalidOperationException(e.Message, e);
            }
        }

        public void WriteString(String str)
        {
            WriteBlock(Strings.ToByteArray(str));
        }

        public byte[] GetBytes()
        {
            return bos.ToArray();
        }

        public byte[] GetPaddedBytes()
        {
            return GetPaddedBytes(8);
        }

        public byte[] GetPaddedBytes(int blockSize)
        {
            int align = (int)bos.Length % blockSize;
            if (0 != align)
            {
                int padCount = blockSize - align;
                for (int i = 1; i <= padCount; ++i)
                {
                    bos.WriteByte(Convert.ToByte(i));
                }
            }
            return bos.ToArray();
        }
    }
}