001    package com.nimbusds.jose.util;
002    
003    
004    import java.math.BigInteger;
005    
006    
007    /**
008     * Big integer utilities.
009     *
010     * @author Vladimir Dzhuvinov
011     * @version $version$ (2013-03-21)
012     */
013    public class BigIntegerUtils {
014    
015    
016            /**
017             * Returns a byte array representation of the specified big integer 
018             * without the sign bit.
019             * 
020             * @param bigInt The big integer to be converted. Must not be
021             *               {@code null}.
022             *
023             * @return A byte array representation of the big integer, without the
024             *         sign bit.
025             */
026            public static byte[] toBytesUnsigned(final BigInteger bigInt) {
027    
028                    // Copied from Apache Commons Codec 1.8
029    
030                    int bitlen = bigInt.bitLength();
031    
032                    // round bitlen
033                    bitlen = ((bitlen + 7) >> 3) << 3;
034                    final byte[] bigBytes = bigInt.toByteArray();
035    
036                    if (((bigInt.bitLength() % 8) != 0) && (((bigInt.bitLength() / 8) + 1) == (bitlen / 8))) {
037                    
038                            return bigBytes;
039                    
040                    }
041    
042                    // set up params for copying everything but sign bit
043                    int startSrc = 0;
044                    int len = bigBytes.length;
045    
046                    // if bigInt is exactly byte-aligned, just skip signbit in copy
047                    if ((bigInt.bitLength() % 8) == 0) {
048                            
049                            startSrc = 1;
050                            len--;
051                    }
052                    
053                    final int startDst = bitlen / 8 - len; // to pad w/ nulls as per spec
054                    final byte[] resizedBytes = new byte[bitlen / 8];
055                    System.arraycopy(bigBytes, startSrc, resizedBytes, startDst, len);
056                    return resizedBytes;
057            }
058    
059    
060            /**
061             * Prevents public instantiation.
062             */
063            private BigIntegerUtils() {
064    
065            }
066    }