diff options
Diffstat (limited to 'crypto/src/util/BigIntegers.cs')
-rw-r--r-- | crypto/src/util/BigIntegers.cs | 45 |
1 files changed, 39 insertions, 6 deletions
diff --git a/crypto/src/util/BigIntegers.cs b/crypto/src/util/BigIntegers.cs index 6674750bb..bac5f12c0 100644 --- a/crypto/src/util/BigIntegers.cs +++ b/crypto/src/util/BigIntegers.cs @@ -15,7 +15,7 @@ namespace Org.BouncyCastle.Utilities /** * Return the passed in value as an unsigned byte array. * - * @param value value to be converted. + * @param value the value to be converted. * @return a byte array without a leading zero byte if present in the signed encoding. */ public static byte[] AsUnsignedByteArray( @@ -25,11 +25,11 @@ namespace Org.BouncyCastle.Utilities } /** - * Return the passed in value as an unsigned byte array of specified length, zero-extended as necessary. - * - * @param length desired length of result array. - * @param n value to be converted. - * @return a byte array of specified length, with leading zeroes as necessary given the size of n. + * Return the passed in value as an unsigned byte array of the specified length, padded with + * leading zeros as necessary. + * @param length the fixed length of the result. + * @param n the value to be converted. + * @return a byte array padded to a fixed length with leading zeros. */ public static byte[] AsUnsignedByteArray(int length, BigInteger n) { @@ -46,6 +46,39 @@ namespace Org.BouncyCastle.Utilities return tmp; } + /** + * Write the passed in value as unsigned bytes to the specified buffer range, padded with + * leading zeros as necessary. + * + * @param value + * the value to be converted. + * @param buf + * the buffer to which the value is written. + * @param off + * the start offset in array <code>buf</code> at which the data is written. + * @param len + * the fixed length of data written (possibly padded with leading zeros). + */ + public static void AsUnsignedByteArray(BigInteger value, byte[] buf, int off, int len) + { + byte[] bytes = value.ToByteArrayUnsigned(); + if (bytes.Length == len) + { + Array.Copy(bytes, 0, buf, off, len); + return; + } + + int start = bytes[0] == 0 ? 1 : 0; + int count = bytes.Length - start; + + if (count > len) + throw new ArgumentException("standard length exceeded for value"); + + int padLen = len - count; + Arrays.Fill(buf, off, off + padLen, 0); + Array.Copy(bytes, start, buf, off + padLen, count); + } + /// <summary> /// Creates a Random BigInteger from the secure random of a given bit length. /// </summary> |