001/* 002 * nimbus-jose-jwt 003 * 004 * Copyright 2012-2016, Connect2id Ltd. 005 * 006 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use 007 * this file except in compliance with the License. You may obtain a copy of the 008 * License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, software distributed 013 * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 014 * CONDITIONS OF ANY KIND, either express or implied. See the License for the 015 * specific language governing permissions and limitations under the License. 016 */ 017 018package com.nimbusds.jose.util; 019 020 021import java.math.BigInteger; 022 023 024/** 025 * Big integer utilities. 026 * 027 * @author Vladimir Dzhuvinov 028 * @version 2013-03-21 029 */ 030public class BigIntegerUtils { 031 032 033 /** 034 * Returns a byte array representation of the specified big integer 035 * without the sign bit. 036 * 037 * @param bigInt The big integer to be converted. Must not be 038 * {@code null}. 039 * 040 * @return A byte array representation of the big integer, without the 041 * sign bit. 042 */ 043 public static byte[] toBytesUnsigned(final BigInteger bigInt) { 044 045 // Copied from Apache Commons Codec 1.8 046 047 int bitlen = bigInt.bitLength(); 048 049 // round bitlen 050 bitlen = ((bitlen + 7) >> 3) << 3; 051 final byte[] bigBytes = bigInt.toByteArray(); 052 053 if (((bigInt.bitLength() % 8) != 0) && (((bigInt.bitLength() / 8) + 1) == (bitlen / 8))) { 054 055 return bigBytes; 056 057 } 058 059 // set up params for copying everything but sign bit 060 int startSrc = 0; 061 int len = bigBytes.length; 062 063 // if bigInt is exactly byte-aligned, just skip signbit in copy 064 if ((bigInt.bitLength() % 8) == 0) { 065 066 startSrc = 1; 067 len--; 068 } 069 070 final int startDst = bitlen / 8 - len; // to pad w/ nulls as per spec 071 final byte[] resizedBytes = new byte[bitlen / 8]; 072 System.arraycopy(bigBytes, startSrc, resizedBytes, startDst, len); 073 return resizedBytes; 074 } 075 076 077 /** 078 * Prevents public instantiation. 079 */ 080 private BigIntegerUtils() { 081 082 } 083}