org.apache.mina.util.Base64 Java Examples

The following examples show how to use org.apache.mina.util.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: CipherManager.java    From gameserver with Apache License 2.0 6 votes vote down vote up
/**
 * Generate the encrypted user token for client to 
 * do reconnect.
 * 
 * @return
 */
public String generateEncryptedUserToken(UserId userId) {
	byte[] userIdBytes = userId.getInternal();
	long timeMillis = System.currentTimeMillis();
	ByteBuffer buf = ByteBuffer.allocate(userIdBytes.length + 8);
	buf.putLong(timeMillis);
	buf.put(userIdBytes);
	byte[] finalBytes = buf.array();
	
	try {
		Cipher cipher = Cipher.getInstance(ALGORITHM);
		cipher.init(Cipher.ENCRYPT_MODE, this.key);
		byte[] encrypted = cipher.doFinal(finalBytes);
		String base64 = new String(Base64.encodeBase64(encrypted));
		return base64;
	} catch (Exception e) {
		logger.warn("generateEncryptedUserToken exception", e);
	}
	return Constant.EMPTY;
}
 
Example #2
Source File: CipherManager.java    From gameserver with Apache License 2.0 6 votes vote down vote up
public String generateEncryptedUserToken(String id) {
	byte[] userIdBytes = id.getBytes();
	long timeMillis = System.currentTimeMillis();
	ByteBuffer buf = ByteBuffer.allocate(userIdBytes.length + 8);
	buf.putLong(timeMillis);
	buf.put(userIdBytes);
	byte[] finalBytes = buf.array();
	
	try {
		Cipher cipher = Cipher.getInstance(ALGORITHM);
		cipher.init(Cipher.ENCRYPT_MODE, this.key);
		byte[] encrypted = cipher.doFinal(finalBytes);
		String base64 = new String(Base64.encodeBase64(encrypted));
		return base64;
	} catch (Exception e) {
		logger.warn("generateEncryptedUserToken exception", e);
	}
	return Constant.EMPTY;
}
 
Example #3
Source File: CipherManager.java    From gameserver with Apache License 2.0 6 votes vote down vote up
/**
 * Check if the token is valid. True if it is. False otherwise.
 * @param token
 * @return
 */
public UserId checkEncryptedUserToken(String token) {
	if ( !StringUtil.checkNotEmpty(token) ) return null;
	byte[] encrypted = Base64.decodeBase64(token.getBytes());
	try {
		Cipher cipher = Cipher.getInstance(ALGORITHM);
		cipher.init(Cipher.DECRYPT_MODE, this.key);
		byte[] textBytes = cipher.doFinal(encrypted);
		ByteBuffer buf = ByteBuffer.wrap(textBytes);
		long timeMillis = buf.getLong();
		byte[] userIdBytes = new byte[buf.remaining()];
		buf.get(userIdBytes);
		UserId userId = UserId.fromBytes(userIdBytes);
		if ( userId != null && timeMillis + CipherManager.timeout > System.currentTimeMillis() ) {
			return userId;
		} else {
			logger.debug("User's token is timeout");
		}
	} catch (Exception e) {
		logger.debug("checkEncryptedUserToken exception: {} ", e.getMessage());
		logger.debug("User's token is invalid");
	}
	return null;
}
 
Example #4
Source File: CipherManager.java    From gameserver with Apache License 2.0 6 votes vote down vote up
/**
 * Check if the token is valid. True if it is. False otherwise.
 * @param token
 * @return
 */
public Account checkEncryptedAccountToken(String token) {
	if ( !StringUtil.checkNotEmpty(token) ) return null;
	byte[] encrypted = Base64.decodeBase64(token.getBytes());
	try {
		Cipher cipher = Cipher.getInstance(ALGORITHM);
		cipher.init(Cipher.DECRYPT_MODE, this.key);
		byte[] textBytes = cipher.doFinal(encrypted);
		ByteBuffer buf = ByteBuffer.wrap(textBytes);
		long timeMillis = buf.getLong();
		byte[] accountIdBytes = new byte[buf.remaining()];
		buf.get(accountIdBytes);
		if ( accountIdBytes != null && accountIdBytes.length>0 && 
				timeMillis + CipherManager.timeout > System.currentTimeMillis() ) {
			String accountId = new String(accountIdBytes);
			Account account = AccountManager.getInstance().queryAccountById(accountId);
			return account;
		} else {
			logger.debug("Account's token is timeout");
		}
	} catch (Exception e) {
		logger.debug("checkEncryptedUserToken exception: {} ", e.getMessage());
		logger.debug("Account's token is invalid");
	}
	return null;
}
 
Example #5
Source File: CodeGenerator_new.java    From sailfish-core with Apache License 2.0 5 votes vote down vote up
private void parseErrors(String error)
{
	if (error.contains(ERROR_HOOK))
	{
		String[] lines = error.split("\n");
		for (String line : lines)
		{
			if (line.contains(ERROR_HOOK))
			{
				int index = line.indexOf(ERROR_HOOK);
				index += ERROR_HOOK.length()+1;
				String data = line.substring(index);
				String[] vals = StringUtil.split(data, ":");
				String base64 = StringUtil.join(":", vals, 4);
				byte[] bytes = Base64.decodeBase64(base64.getBytes());
				String value = new String(bytes);
				error = "Invalid value in column '"+vals[3]+"': "+value;
				if (!alertCollector.contains(AlertType.ERROR, error)) {
                       alertCollector.add(new Alert(Long.parseLong(vals[0]), Long.parseLong(vals[1]), vals[2], vals[3], error));
				}
			}
		}
		return;
	}
       alertCollector.add(new Alert(error));

}
 
Example #6
Source File: UUIDCheck.java    From gameserver with Apache License 2.0 5 votes vote down vote up
public static ScriptResult func(Object[] parameters) {
	ScriptResult result = ScriptManager.checkParameters(parameters, 2);
	if ( result != null ) {
		return result;
	}
	boolean checkPass = true;

	IoSession session = (IoSession)parameters[0];
	String uuid = (String)parameters[1];
	
	//Check client version first
	String base64Uuid = new String(Base64.encodeBase64(uuid.getBytes()));
	if ( uuidSet.contains(uuid) || uuidSet.contains(base64Uuid) ) {
		BseLogin.Builder rep = BseLogin.newBuilder();
		rep.setCode(ErrorCode.S_PAUSE.ordinal());
		rep.setDesc(message);
		XinqiMessage response = new XinqiMessage();
		response.payload = rep.build();
		session.write(response);

		SysMessageManager.getInstance().sendClientInfoRawMessage(session, message, Action.NOOP, Type.CONFIRM);

		checkPass = false;
	}

	ArrayList list = new ArrayList();
	list.add(checkPass);
	
	result = new ScriptResult();
	result.setType(ScriptResult.Type.SUCCESS_RETURN);
	result.setResult(list);
	return result;
}
 
Example #7
Source File: WebsocketHandler.java    From cim with Apache License 2.0 5 votes vote down vote up
@Override
public void process(CIMSession session, SentBody body) {
	session.setChannel(CIMSession.CHANNEL_BROWSER);
	String secKey = body.get("key") + GUID;
	try {
		MessageDigest md = MessageDigest.getInstance("SHA-1");
		md.update(secKey.getBytes(StandardCharsets.ISO_8859_1), 0, secKey.length());
		byte[] sha1Hash = md.digest();

		session.write(new HandshakerResponse(new String(Base64.encodeBase64(sha1Hash))));
	} catch (Exception ignore) {}
}
 
Example #8
Source File: CodeGenerator_new.java    From sailfish-core with Apache License 2.0 4 votes vote down vote up
private void testCode(List<AMLTestCase> testCases) throws WorkspaceSecurityException, AMLException, FileNotFoundException, IOException {
    progressChanged(60);

    List<SetterInfo> setters = new ArrayList<>();

    for(AMLTestCase testCase : testCases) {
        for(AMLAction action : testCase.getActions()) {
            for(Pair<String, String> setter : action.getSetters()) {
                String column = setter.getFirst();
                String code = setter.getSecond();
                Value element = action.getParameters().get(column);
                String value = element.getValue();
                String reference = ObjectUtils.defaultIfNull(action.getReference(), action.getReferenceToFilter());

                StringUtils.removeStart(value, BoolExp.NotEqualsUnary.getName());
                value = new String(Base64.encodeBase64(value.getBytes()));
                SetterInfo info = new SetterInfo(column, code, value, element.getLineNumber(), action.getUID(), reference);

                setters.add(info);
            }
        }
    }

    int count = 0;

    for(List<SetterInfo> subList : Iterables.partition(setters, MAX_SETTERS_PER_CLASS)) {
        String className = "TestClass" + count++;
        File javaFile = workspaceDispatcher.createFile(FolderType.REPORT, true, amlSettings.getBaseDir(), className + ".java");
        File classFile = workspaceDispatcher.createFile(FolderType.REPORT, true, amlSettings.getBaseDir(), className + ".class");

        try(TextOutputStream stream = new TextOutputStream(new FileOutputStream(javaFile))) {
            tcCodeBuilder.writeTestClass(stream, className, subList);
            String error = compileTest(javaFile, classFile);

            if(error == null) {
                continue;
            }

            parseErrors(error);
        }
    }

    progressChanged(70);
}
 
Example #9
Source File: HttpNTLMAuthLogicHandler.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void doHandshake(NextFilter nextFilter) throws ProxyAuthException {
    LOGGER.debug(" doHandshake()");

    if (step > 0 && challengePacket == null) {
        throw new IllegalStateException("NTLM Challenge packet not received");
    }

    HttpProxyRequest req = (HttpProxyRequest) request;
    Map<String, List<String>> headers = req.getHeaders() != null ? req.getHeaders()
            : new HashMap<String, List<String>>();

    String domain = req.getProperties().get(HttpProxyConstants.DOMAIN_PROPERTY);
    String workstation = req.getProperties().get(HttpProxyConstants.WORKSTATION_PROPERTY);

    if (step > 0) {
        LOGGER.debug("  sending NTLM challenge response");

        byte[] challenge = NTLMUtilities.extractChallengeFromType2Message(challengePacket);
        int serverFlags = NTLMUtilities.extractFlagsFromType2Message(challengePacket);

        String username = req.getProperties().get(HttpProxyConstants.USER_PROPERTY);
        String password = req.getProperties().get(HttpProxyConstants.PWD_PROPERTY);

        byte[] authenticationPacket = NTLMUtilities.createType3Message(username, password, challenge, domain,
                workstation, serverFlags, null);

        StringUtilities.addValueToHeader(headers, "Proxy-Authorization",
                "NTLM " + new String(Base64.encodeBase64(authenticationPacket)), true);

    } else {
        LOGGER.debug("  sending NTLM negotiation packet");

        byte[] negotiationPacket = NTLMUtilities.createType1Message(workstation, domain, null, null);
        StringUtilities.addValueToHeader(headers, "Proxy-Authorization",
                "NTLM " + new String(Base64.encodeBase64(negotiationPacket)), true);
    }

    addKeepAliveHeaders(headers);
    req.setHeaders(headers);

    writeRequest(nextFilter, req);
    step++;
}
 
Example #10
Source File: HttpBasicAuthLogicHandler.java    From neoscada with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * Computes the authorization header value.
 * 
 * @param username the user name
 * @param password the user password
 * @return the authorization header value as a string
 */
public static String createAuthorization(final String username, final String password) {
    return new String(Base64.encodeBase64((username + ":" + password).getBytes()));
}