文字列形式のSIDをバイナリ表現に変換する
ここを参考に、文字列形式のSIDをバイナリに変換する関数を書きました。
/** * SIDをバイナリにする。 * @param sid 文字列形式のSID 例) S-1-5-21-2127521184-1604012920-1887927527-72713 * @return SIDのバイナリ表現 */ public static byte[] sidToBytes( String sid ) { String[] steps = sid.replaceFirst("S\\-", "" ).split( "-" ); byte[] bytes = new byte[8+(steps.length-2)*4]; byte[] tmp; for ( int i = 0; i < steps.length; i++ ) { switch (i) { case 0: bytes[0] = toBytes( Long.valueOf( steps[0] ),1, true)[0]; bytes[1] = toBytes( steps.length-2,1, true)[0]; break; case 1: tmp = toBytes( Long.valueOf( steps[1] ),6, false); System.arraycopy( tmp, 0, bytes, 2, 6 ); break; default: tmp = toBytes( Long.valueOf( steps[i] ),4, true); System.arraycopy( tmp, 0, bytes, 8+4*(i-2), 4 ); break; } } return bytes; } private static final byte[] toBytes( long l, int length, boolean little ) { byte[] bs = new byte[length]; for( int i = 0; i < length; i++ ) { byte b = (byte) ((l & 0xFF << i*8) >> i*8 ); bs[little ? i : length-1-i ] = b; } return bs; }
テストケース。もちろん通ります。
/** * {@link Util#sidToBytes(String)}のテスト */ @Test public void testSidToBytes() { assertEquals( toHex(ModelUtil.sidToBytes( "S-1-5-21-2127521184-1604012920-1887927527-72713") ), "010500000000000515000000A065CF7E784B9B5FE77C8770091C0100"); assertEquals( toHex(ModelUtil.sidToBytes( "S-1-5-21-3164429677-3908231522-537588299-1157") ), "0105000000000005150000006D5D9DBC62E1F2E84BF20A2085040000"); assertEquals( toHex(ModelUtil.sidToBytes( "S-1-5-19") ), "010100000000000513000000"); } private String toHex(byte[] bs) { StringBuilder buff = new StringBuilder(bs.length*2); for ( byte b : bs ) { buff.append( String.format("%1$02X", b)); } return buff.toString(); }
テストパターンはもうちょい増やさないとダメだな。あと、異常系の実装とテストも。