Key { public static Key decodeKey(String encodedKey) throws InvalidKeyException { String[] keyArray = encodedKey.split(Key.separator); if (keyArray.length != 2) { throw new InvalidKeyException("Does not contain a valid key format"); } String keyType = keyArray[0]; String keyContent = keyArray[1]; if (!keyContent.matches("[0-9a-fA-F]{64}")) { throw new InvalidKeyException("Does not contain a valid key"); } return new Key(keyType, DataUtils.hexStringToByteArray(keyContent)); } Key(String type, byte[] key); static Key decodeKey(String encodedKey); static Key decodeKey(String encodedKey, String expectedKeyType); String encode(); static final String separator; public byte[] key; public String type; }
@Test public void testDecodeWrongKey() { try { Key.decodeKey("imnotarealkey"); } catch (InvalidKeyException e) { return; } Assert.assertFalse("could parse invalid key", true); }
@Test public void testDecodeKeyPrivate() throws Exception { Key key = Key.decodeKey("private:1234567890123456789012345678901234567890123456789012345678901234"); Assert.assertNotNull("key instance", key); Assert.assertEquals(key.type, Key.KeyType.PRIVATE); Assert.assertEquals(key.key, DataUtils.hexStringToByteArray("1234567890123456789012345678901234567890123456789012345678901234")); }
@Test public void testDecodeKeyPublic() throws Exception { Key key = Key.decodeKey("public:1234567890123456789012345678901234567890123456789012345678901234"); Assert.assertNotNull("key instance", key); Assert.assertEquals(key.type, Key.KeyType.PUBLIC); Assert.assertEquals(key.key, DataUtils.hexStringToByteArray("1234567890123456789012345678901234567890123456789012345678901234")); }