net.iharder.Base64 Java Examples

The following examples show how to use net.iharder.Base64. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: S256CodeChallenge.java    From oauth2-essentials with Apache License 2.0 6 votes vote down vote up
@Override
public CharSequence challenge()
{
    try
    {
        String result = Base64.encodeBytes(new Digest(new Sha256(), mCodeVerifier).value(), Base64.URL_SAFE);
        // Note, the code challenge parameter doesn't support equals chars, so we have to remove any padding
        if (result.endsWith("=="))
        {
            return result.substring(0, result.length() - 2);
        }
        if (result.endsWith("="))
        {
            return result.substring(0, result.length() - 1);
        }
        return result;
    }
    catch (IOException e)
    {
        throw new RuntimeException("IOException while operating on strings");
    }
}
 
Example #2
Source File: EntityNBTBase.java    From NBTEditor with GNU General Public License v3.0 6 votes vote down vote up
public static EntityNBT unserialize(String serializedData) {
	try {
		NBTTagCompound data = NBTTagCompound.unserialize(Base64.decode(serializedData));

		// Backward compatibility with pre-1.9.
		// On 1.9 the entities are stacked for bottom to top.
		// This conversion needs to happen before instantiating any class, we cannot use onUnserialize.
		while (data.hasKey("Riding")) {
			NBTTagCompound riding = data.getCompound("Riding");
			data.remove("Riding");
			riding.setList("Passengers", new NBTTagList(data));
			data = riding;
		}

		return fromEntityData(data);
	} catch (Throwable e) {
		throw new RuntimeException("Error unserializing EntityNBT.", e);
	}
}
 
Example #3
Source File: MusicController.java    From lavaplayer with Apache License 2.0 6 votes vote down vote up
@BotCommandHandler
private void deserialize(Message message, String content) throws IOException {
  outputChannel.set((TextChannel) message.getChannel());
  connectToFirstVoiceChannel(guild.getAudioManager());

  byte[] bytes = Base64.decode(content);

  MessageInput inputStream = new MessageInput(new ByteArrayInputStream(bytes));
  DecodedTrackHolder holder;

  while ((holder = manager.decodeTrack(inputStream)) != null) {
    if (holder.decodedTrack != null) {
      scheduler.addToQueue(holder.decodedTrack);
    }
  }
}
 
Example #4
Source File: ChaiHelpdeskAnswer.java    From ldapchai with GNU Lesser General Public License v2.1 6 votes vote down vote up
private static String encryptValue( final String value, final String key )
        throws ChaiOperationException
{
    try
    {
        if ( value == null || value.length() < 1 )
        {
            return "";
        }

        final SecretKey secretKey = makeKey( key );
        final Cipher cipher = Cipher.getInstance( "AES" );
        cipher.init( Cipher.ENCRYPT_MODE, secretKey, cipher.getParameters() );
        final byte[] encrypted = cipher.doFinal( value.getBytes() );
        return Base64.encodeBytes( encrypted, Base64.URL_SAFE | Base64.GZIP );
    }
    catch ( Exception e )
    {
        final String errorMsg = "unexpected error performing helpdesk answer crypt operation: " + e.getMessage();
        throw new ChaiOperationException( errorMsg, ChaiError.CHAI_INTERNAL_ERROR );
    }
}
 
Example #5
Source File: ChaiHelpdeskAnswer.java    From ldapchai with GNU Lesser General Public License v2.1 6 votes vote down vote up
private static String decryptValue( final String value, final String key )
{
    try
    {
        if ( value == null || value.length() < 1 )
        {
            return "";
        }

        final SecretKey secretKey = makeKey( key );
        final byte[] decoded = Base64.decode( value, Base64.URL_SAFE | Base64.GZIP );
        final Cipher cipher = Cipher.getInstance( "AES" );
        cipher.init( Cipher.DECRYPT_MODE, secretKey );
        final byte[] decrypted = cipher.doFinal( decoded );
        return new String( decrypted );
    }
    catch ( Exception e )
    {
        final String errorMsg = "unexpected error performing helpdesk answer decrypt operation: " + e.getMessage();
        throw new IllegalArgumentException( errorMsg );
    }
}
 
Example #6
Source File: IndexerDefinitionJsonSerDeser.java    From hbase-indexer with Apache License 2.0 5 votes vote down vote up
private void setByteArrayProperty(ObjectNode node, String property, byte[] data) {
    if (data == null)
        return;
    try {
        node.put(property, Base64.encodeBytes(data, Base64.GZIP));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #7
Source File: KeyGenerator.java    From syndesis with Apache License 2.0 5 votes vote down vote up
/**
 * Used to extract the time information that is encoded to each
 * generated key.
 */
public static long getKeyTimeMillis(String key) throws IOException {
    byte[] decoded = Base64.decode(stripPreAndSuffix(key), Base64.ORDERED);
    if (decoded.length != 15) {
        throw new IOException("Invalid key: size is incorrect.");
    }
    ByteBuffer buffer = ByteBuffer.allocate(8);
    buffer.position(2);
    buffer.put(decoded, 0 ,6);
    buffer.flip();
    return buffer.getLong();
}
 
Example #8
Source File: IndexerDefinitionJsonSerDeser.java    From hbase-indexer with Apache License 2.0 5 votes vote down vote up
private byte[] getByteArrayProperty(ObjectNode node, String property) {
    try {
        String string = JsonUtil.getString(node, property, null);
        if (string == null)
            return null;
        return Base64.decode(string);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #9
Source File: BookOfSouls.java    From NBTEditor with GNU General Public License v3.0 5 votes vote down vote up
public static EntityNBT bookToEntityNBT(ItemStack book) {
	if (isValidBook(book)) {
		try {
			String data = BookSerialize.loadData((BookMeta) book.getItemMeta(), _dataTitle);
			if (data == null) {
				// This is not a BoS v0.2, is BoS v0.1?
				data = BookSerialize.loadData((BookMeta) book.getItemMeta(), _dataTitleOLD);
				if (data != null) {
					// Yes, it is v0.1, do a dirty conversion.
					int i = data.indexOf(',');
					NBTTagCompound nbtData = NBTTagCompound.unserialize(Base64.decode(data.substring(i + 1)));
					nbtData.setString("id", data.substring(0, i));
					data = Base64.encodeBytes(nbtData.serialize(), Base64.GZIP);
				}
			}
			if (data != null) {
				if (data.startsWith("§k")) {
					// Dirty fix, for some reason 'data' can sometimes start with §k.
					// Remove it!!!
					data = data.substring(2);
				}
				return EntityNBT.unserialize(data);
			}
		} catch (Exception e) {
			_plugin.getLogger().log(Level.WARNING, "Corrupt Book of Souls.", e);
			return null;
		}
	}
	return null;
}
 
Example #10
Source File: EntityNBTBase.java    From NBTEditor with GNU General Public License v3.0 5 votes vote down vote up
public String serialize() {
	try {
		return Base64.encodeBytes(_data.serialize(), Base64.GZIP);
	} catch (Throwable e) {
		throw new RuntimeException("Error serializing EntityNBT.", e);
	}
}
 
Example #11
Source File: AbstractChaiEntry.java    From ldapchai with GNU Lesser General Public License v2.1 5 votes vote down vote up
public String readGUID()
        throws ChaiOperationException, ChaiUnavailableException
{
    final byte[][] guidValues = this.readMultiByteAttribute( "guid" );
    if ( guidValues == null || guidValues.length < 1 )
    {
        return null;
    }
    final byte[] guidValue = guidValues[0];
    return Base64.encodeBytes( guidValue );
}
 
Example #12
Source File: HashSaltAnswer.java    From ldapchai with GNU Lesser General Public License v2.1 5 votes vote down vote up
static String doHash(
        final String input,
        final int hashCount,
        final FormatType formatType,
        final VERSION version
)
        throws IllegalStateException
{
    final String algorithm = SUPPORTED_FORMATS.get( formatType );
    final MessageDigest md;
    try
    {
        md = MessageDigest.getInstance( algorithm );
    }
    catch ( NoSuchAlgorithmException e )
    {
        throw new IllegalStateException( "unable to load " + algorithm + " message digest algorithm: " + e.getMessage() );
    }


    byte[] hashedBytes = input.getBytes();
    switch ( version )
    {
        case A:
            hashedBytes = md.digest( hashedBytes );
            return Base64.encodeBytes( hashedBytes );

        case B:
            for ( int i = 0; i < hashCount; i++ )
            {
                hashedBytes = md.digest( hashedBytes );
            }
            return Base64.encodeBytes( hashedBytes );

        default:
            throw new IllegalStateException( "unexpected version enum in hash method" );
    }
}
 
Example #13
Source File: MusicController.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
@BotCommandHandler
private void serialize(Message message) throws IOException {
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  MessageOutput outputStream = new MessageOutput(baos);

  for (AudioTrack track : scheduler.drainQueue()) {
    manager.encodeTrack(outputStream, track);
  }

  outputStream.finish();

  message.getChannel().sendMessage(Base64.encodeBytes(baos.toByteArray())).queue();
}
 
Example #14
Source File: BasicAuthHeaderDecorationTest.java    From oauth2-essentials with Apache License 2.0 5 votes vote down vote up
@Test
public void test_thatExistingAuthHeaderIsOverridden() throws Exception
{
    // ARRANGE
    Headers original = EmptyHeaders.INSTANCE.withHeader(AUTHORIZATION_HEADER_TYPE.entity("dummy auth header value"));
    BasicAuthHeaderDecoration decoration = new BasicAuthHeaderDecoration("user_name", "pw");

    // ACT
    Headers result = decoration.decorated(original);

    // ASSERT
    String expectedHeader = "Basic " + Base64.encodeBytes("user_name:pw".getBytes("UTF-8"));
    assertEquals(expectedHeader, result.header(AUTHORIZATION_HEADER_TYPE).value());
}
 
Example #15
Source File: BasicAuthHeaderDecorationTest.java    From oauth2-essentials with Apache License 2.0 5 votes vote down vote up
@Test
public void test_thatCorrectAuthHeaderGetsAdded_andOtherHeaderIsKept() throws Exception
{
    // ARRANGE
    Headers original = EmptyHeaders.INSTANCE.withHeader(HttpHeaders.CONTENT_LENGTH.entity(45));
    BasicAuthHeaderDecoration decoration = new BasicAuthHeaderDecoration("user_name", "pw");

    // ACT
    Headers result = decoration.decorated(original);

    // ASSERT
    String expectedHeader = "Basic " + Base64.encodeBytes("user_name:pw".getBytes("UTF-8"));
    assertEquals(expectedHeader, result.header(AUTHORIZATION_HEADER_TYPE).value());
    assertTrue(result.contains(HttpHeaders.CONTENT_LENGTH));
}
 
Example #16
Source File: KeyGenerator.java    From syndesis with Apache License 2.0 5 votes vote down vote up
private static String encodeKey(byte[] data) {
    try {
        return "i" + Base64.encodeBytes(data, 2, 15, Base64.ORDERED) + "z";
    } catch (final IOException e) {
        throw new SyndesisServerException(e);
    }
}
 
Example #17
Source File: Utils.java    From netbeans-mmd-plugin with Apache License 2.0 4 votes vote down vote up
@Nonnull
public static byte[] base64decode(@Nonnull final String text) throws IOException {
  return Base64.decode(text);
}
 
Example #18
Source File: Utils.java    From netbeans-mmd-plugin with Apache License 2.0 4 votes vote down vote up
@Nonnull
public static String base64encode(@Nonnull final byte[] data) {
  return Base64.encodeBytes(data);
}
 
Example #19
Source File: JsonRpcBasicServer.java    From jsonrpc4j with MIT License 4 votes vote down vote up
/**
 * Returns parameters into an {@link InputStream} of JSON data.
 *
 * @param method the method
 * @param id     the id
 * @param params the base64 encoded params
 * @return the {@link InputStream}
 * @throws IOException on error
 */
static InputStream createInputStream(String method, String id, String params) throws IOException {
	
	StringBuilder envelope = new StringBuilder();
	
	envelope.append("{\"");
	envelope.append(JSONRPC);
	envelope.append("\":\"");
	envelope.append(VERSION);
	envelope.append("\",\"");
	envelope.append(ID);
	envelope.append("\":");
	
	// the 'id' value is assumed to be numerical.
	
	if (null != id && !id.isEmpty()) {
		envelope.append(id);
	} else {
		envelope.append("null");
	}
	
	envelope.append(",\"");
	envelope.append(METHOD);
	envelope.append("\":");
	
	if (null != method && !method.isEmpty()) {
		envelope.append('"');
		envelope.append(method);
		envelope.append('"');
	} else {
		envelope.append("null");
	}
	envelope.append(",\"");
	envelope.append(PARAMS);
	envelope.append("\":");
	
	if (null != params && !params.isEmpty()) {
		String decodedParams;
		
		// some specifications suggest that the GET "params" query parameter should be Base64 encoded and
		// some suggest not.  Try to deal with both scenarios -- the code here was previously only doing
		// Base64 decoding.
		// http://www.simple-is-better.org/json-rpc/transport_http.html
		// http://www.jsonrpc.org/historical/json-rpc-over-http.html#encoded-parameters
		
		if (BASE64_PATTERN.matcher(params).matches()) {
			decodedParams = new String(Base64.decode(params), StandardCharsets.UTF_8);
		} else {
			switch (params.charAt(0)) {
				case '[':
				case '{':
					decodedParams = params;
					break;
				
				default:
					throw new IOException("badly formed 'param' parameter starting with; [" + params.charAt(0) + "]");
			}
		}
		
		envelope.append(decodedParams);
	} else {
		envelope.append("[]");
	}
	
	envelope.append('}');
	
	return new ByteArrayInputStream(envelope.toString().getBytes(StandardCharsets.UTF_8));
}
 
Example #20
Source File: BasicAuthHeaderDecoration.java    From oauth2-essentials with Apache License 2.0 4 votes vote down vote up
@Override
public Headers decorated(Headers original)
{
    String authHeaderValue = "Basic " + Base64.encodeBytes(usernameAndPasswordBytes());
    return new UpdatedHeaders(original, AUTHORIZATION_HEADER_TYPE.entity(authHeaderValue));
}