• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Java Base64类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Java中org.apache.mina.util.Base64的典型用法代码示例。如果您正苦于以下问题:Java Base64类的具体用法?Java Base64怎么用?Java Base64使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



Base64类属于org.apache.mina.util包,在下文中一共展示了Base64类的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Java代码示例。

示例1: generateEncryptedUserToken

import org.apache.mina.util.Base64; //导入依赖的package包/类
/**
 * 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;
}
 
开发者ID:wangqi,项目名称:gameserver,代码行数:26,代码来源:CipherManager.java


示例2: checkEncryptedUserToken

import org.apache.mina.util.Base64; //导入依赖的package包/类
/**
 * 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;
}
 
开发者ID:wangqi,项目名称:gameserver,代码行数:29,代码来源:CipherManager.java


示例3: checkEncryptedAccountToken

import org.apache.mina.util.Base64; //导入依赖的package包/类
/**
 * 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;
}
 
开发者ID:wangqi,项目名称:gameserver,代码行数:31,代码来源:CipherManager.java


示例4: handleUserSettings

import org.apache.mina.util.Base64; //导入依赖的package包/类
/**
 * Sets the database User Settings and adds packet to queue
 */
public static void handleUserSettings(IoSession session, Packet pktIn,
		Queue<Packet> queue, Connection con) throws MGOException {
	int res = 0;
	byte[] userSettings = pktIn.payload;
	try {
		String encUserSettings = new String(
				Base64.encodeBase64(userSettings));
		int pid = (Integer) session.getAttribute("userid", -1);

		PreparedStatement stmt = con
				.prepareStatement("UPDATE users SET user_settings=? WHERE id=?");
		stmt.setString(1, encUserSettings);
		stmt.setLong(2, pid);
		res = stmt.executeUpdate();
	} catch (SQLException e) {
		throw new MGOException(0x4111, 1, e);
	}
	if (res <= 0) {
		throw new MGOException(0x4111, 2,
				"SQL UPDATE did not affect any users.");
	}

	// Add the OK to the queue
	queue.add(new Packet(0x4111, new byte[4]));
}
 
开发者ID:curi0us,项目名称:mgops,代码行数:29,代码来源:LobbyPlayer.java


示例5: decrypt

import org.apache.mina.util.Base64; //导入依赖的package包/类
@Override
public String decrypt( String encryptedPassword ) throws PasswordServiceException {
  try {
    Cipher decCipher = Cipher.getInstance( secretKey.getAlgorithm() );
    decCipher.init( Cipher.DECRYPT_MODE, secretKey, paramSpec );
    byte[] toDecryptBytes = Base64.decodeBase64( encryptedPassword.getBytes() );
    byte[] decryptedBytes = decCipher.doFinal( toDecryptBytes );
    return new String( decryptedBytes, UTF_8 );
  } catch ( Exception ex ) {
    throw new PasswordServiceException( ex );
  }
}
 
开发者ID:pentaho,项目名称:pentaho-osgi-bundles,代码行数:13,代码来源:CipherEncryptionServiceImpl.java


示例6: encrypt

import org.apache.mina.util.Base64; //导入依赖的package包/类
@Override
public String encrypt( String clearPassword ) throws PasswordServiceException {
  try {
    Cipher encCipher = Cipher.getInstance( secretKey.getAlgorithm() );
    encCipher.init( Cipher.ENCRYPT_MODE, secretKey, paramSpec );
    byte[] toEncryptBytes = clearPassword.getBytes( UTF_8 );
    byte[] encBytes = encCipher.doFinal( toEncryptBytes );
    byte[] base64Bytes = Base64.encodeBase64( encBytes );
    return new String( base64Bytes, UTF_8 );
  } catch ( Exception ex ) {
    throw new PasswordServiceException( ex );
  }
}
 
开发者ID:pentaho,项目名称:pentaho-osgi-bundles,代码行数:14,代码来源:CipherEncryptionServiceImpl.java


示例7: func

import org.apache.mina.util.Base64; //导入依赖的package包/类
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;
}
 
开发者ID:wangqi,项目名称:gameserver,代码行数:34,代码来源:UUIDCheck.java


示例8: handleNewRound

import org.apache.mina.util.Base64; //导入依赖的package包/类
/**
 * Game is going to a new round, update map/rule
 */
public static void handleNewRound(IoSession session, Packet pktIn, Queue<Packet> queue, Connection con) throws MGOException {
	int uid = (Integer) session.getAttribute("userid");
	//Get round index
	IoBuffer iob = IoBuffer.wrap(pktIn.payload);
	byte newRound = iob.get();
	iob.free();

	//Update database
	ResultSet rs = null;
	PreparedStatement stmt = null;
	try {
		//Get Game id
		stmt = con.prepareStatement("SELECT id,misc_data FROM games WHERE host_id=?");
		stmt.setInt(1,uid);
		rs = stmt.executeQuery();
		rs.first();
		int gameid = rs.getInt("id");
		
		byte[] misc = Base64.decodeBase64(rs.getString("misc_data").getBytes());

		//Delete game, due to table relationship with players; players will be deleted automatically
		stmt = con.prepareStatement("UPDATE games SET map=?, rule=? WHERE id=?");
		stmt.setInt(1,misc[(newRound*2)+1]);
		stmt.setInt(2,misc[(newRound*2)]);
		stmt.setInt(3,gameid);
		stmt.executeUpdate();
		//Store rule in host's session so we don't have to query it at end of round
		session.setAttribute("host_rule", misc[(newRound*2)]);
	} catch(SQLException e) {
		//Fail silently, game doesn't care
	}

	//Send reply
	queue.add(new Packet(0x4393,new byte[4]));

}
 
开发者ID:curi0us,项目名称:mgops,代码行数:40,代码来源:LobbyHost.java


示例9: getPastGameSettings

import org.apache.mina.util.Base64; //导入依赖的package包/类
/**
 * Gets the past create game settings
 */
public static void getPastGameSettings(IoSession session, Packet pktIn,
		Queue<Packet> queue, Connection con) throws MGOException {
	int userid = (Integer) session.getAttribute("userid", -1);
	if (userid == -1) {
		throw new MGOException(0x4311, 1, "No User ID in IoSession.");
	}

	String encGameSettings = null;
	PreparedStatement stmt = null;
	try {
		// Prepare the query and set the settings
		stmt = con
				.prepareStatement("SELECT `game_settings` FROM `users` WHERE `id`=? LIMIT 1");
		stmt.setInt(1, userid);
		ResultSet rs = stmt.executeQuery();

		if (rs.next()) {
			encGameSettings = rs.getString("game_settings");
		}
	} catch (SQLException e) {
		throw new MGOException(0x4311, 14, e);
	}

	// Decode the settings
	byte[] gameSettings = (encGameSettings != null) ? Base64
			.decodeBase64(encGameSettings.getBytes()) : new byte[0];

	// Create the payload
	IoBuffer iob = IoBuffer.allocate(266, false);
	iob.putUnsignedInt(0L).put(gameSettings);
	byte[] payload = iob.array();
	iob.free();
	
	// Send it off
	queue.add(new Packet(0x4305, payload));
}
 
开发者ID:curi0us,项目名称:mgops,代码行数:40,代码来源:LobbyGame.java


示例10: doHandshake

import org.apache.mina.util.Base64; //导入依赖的package包/类
/**
 * {@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++;
}
 
开发者ID:eclipse,项目名称:neoscada,代码行数:48,代码来源:HttpNTLMAuthLogicHandler.java


示例11: readRSAPublicKey

import org.apache.mina.util.Base64; //导入依赖的package包/类
private static RSAPublicKey readRSAPublicKey(String keyString) {
	byte[] keyData = Base64.decodeBase64(keyString.getBytes());
	int keyLength = keyData.length;
	int i = 0;
	if (keyLength - i < 4) {
		throw new IllegalArgumentException("Unexpected end of data.");
	}
	int fieldLength = readPositiveInt(keyData, i);
	i += 4;
	if (keyLength - i < fieldLength) {
		throw new IllegalArgumentException("Unexpected end of data.");
	}
	String keyType = new String(keyData, i, fieldLength);
	i += fieldLength;
	if (!keyType.equals("ssh-rsa")) {
		throw new IllegalArgumentException(
				"Specified key is not a valid SSH RSA public key.");
	}
	if (keyLength - i < 4) {
		throw new IllegalArgumentException("Unexpected end of data.");
	}
	fieldLength = readPositiveInt(keyData, i);
	i += 4;
	if (keyLength - i < fieldLength) {
		throw new IllegalArgumentException("Unexpected end of data.");
	}
	final BigInteger exponent = new BigInteger(Arrays.copyOfRange(keyData,
			i, i + fieldLength));
	i += fieldLength;
	if (keyLength - i < 4) {
		throw new IllegalArgumentException("Unexpected end of data.");
	}
	fieldLength = readPositiveInt(keyData, i);
	i += 4;
	if (keyLength - i < fieldLength) {
		throw new IllegalArgumentException("Unexpected end of data.");
	}
	final BigInteger modulus = new BigInteger(Arrays.copyOfRange(keyData,
			i, i + fieldLength));
	i += fieldLength;
	if (i < keyLength) {
		throw new IllegalArgumentException(
				"Unexpcted surplus data at end of key.");
	}
	return new RSAPublicKeyImpl(modulus, exponent);
}
 
开发者ID:litesolutions,项目名称:scm-ssh-plugin,代码行数:47,代码来源:AuthorizedKeysReader.java


示例12: readDSAPublicKey

import org.apache.mina.util.Base64; //导入依赖的package包/类
private static DSAPublicKey readDSAPublicKey(String keyString) {
	byte[] keyData = Base64.decodeBase64(keyString.getBytes());
	int keyLength = keyData.length;
	int i = 0;
	if (keyLength - i < 4) {
		throw new IllegalArgumentException("Unexpected end of data.");
	}
	int fieldLength = readPositiveInt(keyData, i);
	i += 4;
	if (keyLength - i < fieldLength) {
		throw new IllegalArgumentException("Unexpected end of data.");
	}
	String keyType = new String(keyData, i, fieldLength);
	i += fieldLength;
	if (!keyType.equals("ssh-dss")) {
		throw new IllegalArgumentException(
				"Specified key is not a valid SSH DSA public key.");
	}
	if (keyLength - i < 4) {
		throw new IllegalArgumentException("Unexpected end of data.");
	}
	fieldLength = readPositiveInt(keyData, i);
	i += 4;
	if (keyLength - i < fieldLength) {
		throw new IllegalArgumentException("Unexpected end of data.");
	}
	final BigInteger p = new BigInteger(Arrays.copyOfRange(keyData, i, i
			+ fieldLength));
	i += fieldLength;
	if (keyLength - i < 4) {
		throw new IllegalArgumentException("Unexpected end of data.");
	}
	fieldLength = readPositiveInt(keyData, i);
	i += 4;
	if (keyLength - i < fieldLength) {
		throw new IllegalArgumentException("Unexpected end of data.");
	}
	final BigInteger q = new BigInteger(Arrays.copyOfRange(keyData, i, i
			+ fieldLength));
	i += fieldLength;
	if (keyLength - i < 4) {
		throw new IllegalArgumentException("Unexpected end of data.");
	}
	fieldLength = readPositiveInt(keyData, i);
	i += 4;
	if (keyLength - i < fieldLength) {
		throw new IllegalArgumentException("Unexpected end of data.");
	}
	final BigInteger g = new BigInteger(Arrays.copyOfRange(keyData, i, i
			+ fieldLength));
	i += fieldLength;
	if (keyLength - i < 4) {
		throw new IllegalArgumentException("Unexpected end of data.");
	}
	fieldLength = readPositiveInt(keyData, i);
	i += 4;
	if (keyLength - i < fieldLength) {
		throw new IllegalArgumentException("Unexpected end of data.");
	}
	final BigInteger pub = new BigInteger(Arrays.copyOfRange(keyData, i, i
			+ fieldLength));
	i += fieldLength;
	if (i < keyLength) {
		throw new IllegalArgumentException(
				"Unexpcted surplus data at end of key.");
	}
	return new DSAPublicKeyImpl(p, q, g, pub);
}
 
开发者ID:litesolutions,项目名称:scm-ssh-plugin,代码行数:69,代码来源:AuthorizedKeysReader.java


示例13: createAuthorization

import org.apache.mina.util.Base64; //导入依赖的package包/类
/**
 * 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()));
}
 
开发者ID:eclipse,项目名称:neoscada,代码行数:11,代码来源:HttpBasicAuthLogicHandler.java



注:本文中的org.apache.mina.util.Base64类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Java JUnit4Builder类代码示例发布时间:2022-05-22
下一篇:
Java LocalStep类代码示例发布时间:2022-05-22
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap