Java Code Examples for javax.xml.bind.DatatypeConverter#printBase64Binary()

The following examples show how to use javax.xml.bind.DatatypeConverter#printBase64Binary() . 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: PyroProxySerpent.java    From big-c with Apache License 2.0 6 votes vote down vote up
public Map<String, Object> convert(Object obj) {
	// note: the state array returned here must conform to the list consumed by Pyro4's Proxy.__setstate_from_dict__ 
	// that means, we make a list with 8 entries:
	// uri, oneway set, methods set, attrs set, timeout, hmac_key, handshake, maxretries  (in this order)
	PyroProxy proxy = (PyroProxy) obj;
	Map<String, Object> dict = new HashMap<String, Object>();
	String uri = String.format("PYRO:%s@%s:%d", proxy.objectid, proxy.hostname, proxy.port);

	String encodedHmac = proxy.pyroHmacKey!=null? "b64:"+DatatypeConverter.printBase64Binary(proxy.pyroHmacKey) : null;
	dict.put("state", new Object[]{
		uri,
		proxy.pyroOneway,
		proxy.pyroMethods,
		proxy.pyroAttrs,
		0.0,
		encodedHmac,
		proxy.pyroHandshake,
		0   // maxretries is not used/supported in pyrolite
	});
	dict.put("__class__", "Pyro4.core.Proxy");
	return dict;
}
 
Example 2
Source File: CipherTools.java    From rapidminer-studio with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Encrypt the given {@link String} with the specified {@link Key} and encode the result in
 * Base64.
 * 
 * @param text
 * @param key
 * @return
 * @throws CipherException
 */
public static String encrypt(String text, Key key) throws CipherException {
	try {
		Cipher cipher = Cipher.getInstance(CIPHER_TYPE);
		cipher.init(Cipher.ENCRYPT_MODE, key);

		byte[] outputBytes = cipher.doFinal(text.getBytes());

		String base64;
		if (text.length() < FORMER_MINLENGTH_TO_ENCODE) {
			// use new way to encode strings with less than 4 characters which was impossible
			// before 6.0.003
			base64 = DatatypeConverter.printBase64Binary(outputBytes) + FLAG_NEW_ENCODE;
		} else {
			// use old way for full backwards compatibility
			base64 = Base64.encodeBytes(outputBytes);
		}
		return base64;
	} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
		throw new CipherException("Failed to encrypt text: " + e.getMessage());
	}
}
 
Example 3
Source File: HttpTransportPipe.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private void addBasicAuth(Packet context, Map<String, List<String>> reqHeaders) {
    String user = (String) context.invocationProperties.get(BindingProvider.USERNAME_PROPERTY);
    if (user != null) {
        String pw = (String) context.invocationProperties.get(BindingProvider.PASSWORD_PROPERTY);
        if (pw != null) {
            StringBuilder buf = new StringBuilder(user);
            buf.append(":");
            buf.append(pw);
            String creds = DatatypeConverter.printBase64Binary(buf.toString().getBytes());
            reqHeaders.put("Authorization", Collections.singletonList("Basic "+creds));
        }
    }
}
 
Example 4
Source File: CorbaOctetSequenceHandler.java    From cxf with Apache License 2.0 5 votes vote down vote up
public String getDataFromValue() {
    String result;
    if (isBase64Octets) {
        result = new String(DatatypeConverter.printBase64Binary(value));
    } else {
        result = new String(DatatypeConverter.printHexBinary(value));
    }
    return result;
}
 
Example 5
Source File: Base64Utils.java    From mrgeo with Apache License 2.0 5 votes vote down vote up
public static String encodeDoubleArray(double[] noData) throws IOException
{
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  ObjectOutputStream oos = null;
  byte[] rawBytes;
  try
  {
    oos = new ObjectOutputStream(baos);
    oos.writeInt(noData.length);
    for (double nd : noData)
    {
      oos.writeDouble(nd);
    }
    oos.flush();
    rawBytes = baos.toByteArray();
  }
  finally
  {
    if (oos != null)
    {
      oos.close();
    }
    baos.close();
  }

  return DatatypeConverter.printBase64Binary(rawBytes);
}
 
Example 6
Source File: BaseEncryption.java    From geowave with Apache License 2.0 5 votes vote down vote up
/**
 * Method to generate a new random token key value
 *
 * @return
 * @throws Exception
 */
private static String generateRandomSecretKey() throws Exception {
  final KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
  keyGenerator.init(256);
  final SecretKey secretKey = keyGenerator.generateKey();
  final byte[] encoded = secretKey.getEncoded();
  return DatatypeConverter.printBase64Binary(encoded);
}
 
Example 7
Source File: RestRequest.java    From testfun with Apache License 2.0 5 votes vote down vote up
private String getBasicAuthentication() {
    try {
        return "BASIC " + DatatypeConverter.printBase64Binary(basicCreds.getBytes("UTF-8"));
    } catch (UnsupportedEncodingException ex) {
        throw new IllegalStateException("Cannot encode with UTF-8", ex);
    }
}
 
Example 8
Source File: BaseMd5.java    From JgFramework with Apache License 2.0 5 votes vote down vote up
/**
 * 进行MD5加密
 *
 * @param text 原始的SPKEY
 * @return String 指定加密方式为md5后的String
 */
public static String encrypt(String text) {
    byte[] returnByte;
    try {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        returnByte = md5.digest(text.getBytes(Boot.getCharset()));
    } catch (Exception e) {
        return null;
    }
    return DatatypeConverter.printBase64Binary(returnByte);
}
 
Example 9
Source File: ObjectUtils.java    From streamsx.topology with Apache License 2.0 5 votes vote down vote up
public static String serializeLogic(Serializable logic) {

        try {
            ByteArrayOutputStream bao = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bao);
            oos.writeObject(logic);
            oos.flush();
            return DatatypeConverter.printBase64Binary(bao.toByteArray());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
 
Example 10
Source File: QETag.java    From mysiteforme with Apache License 2.0 4 votes vote down vote up
public String urlSafeBase64Encode(byte[] data) {
    String encodedString = DatatypeConverter.printBase64Binary(data);
    encodedString = encodedString.replace('+', '-').replace('/', '_');
    return encodedString;
}
 
Example 11
Source File: Base64.java    From dbvisualizer-agent with GNU General Public License v3.0 4 votes vote down vote up
public static String encodeToString(byte[] src) {
    return DatatypeConverter.printBase64Binary(src);
}
 
Example 12
Source File: ConvertUserFavoriteSitesSakai11.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
private String encodeBase64(String s) throws Exception {
    return DatatypeConverter.printBase64Binary(s.getBytes("UTF-8"));
}
 
Example 13
Source File: Base64Utils.java    From mrgeo with Apache License 2.0 4 votes vote down vote up
public static String encodeObject(Object obj) throws IOException
{
  byte[] bytes = ObjectUtils.encodeObject(obj);
  return DatatypeConverter.printBase64Binary(bytes);
}
 
Example 14
Source File: BasicAuthenticator.java    From jlibs with Apache License 2.0 4 votes vote down vote up
public BasicAuthenticator(String user, String passwd){
    this.user = user;
    this.passwd = passwd;
    String base64UserCredentials = DatatypeConverter.printBase64Binary((user + ":" + passwd).getBytes(Charset.forName("US-ASCII")));
    headerValue = TYPE +" "+ base64UserCredentials;
}
 
Example 15
Source File: Base64.java    From atlassian-agent with GNU General Public License v3.0 4 votes vote down vote up
public static String encode(byte[] data) {
    return DatatypeConverter.printBase64Binary(data);
}
 
Example 16
Source File: DefaultAuthProvider.java    From Openfire with Apache License 2.0 4 votes vote down vote up
@Override
public void setPassword(String username, String password) throws UserNotFoundException {
    // Determine if the password should be stored as plain text or encrypted.
    boolean usePlainPassword = JiveGlobals.getBooleanProperty("user.usePlainPassword");
    boolean scramOnly = JiveGlobals.getBooleanProperty("user.scramHashedPasswordOnly");
    String encryptedPassword = null;
    if (username.contains("@")) {
        // Check that the specified domain matches the server's domain
        int index = username.indexOf("@");
        String domain = username.substring(index + 1);
        if (domain.equals(XMPPServer.getInstance().getServerInfo().getXMPPDomain())) {
            username = username.substring(0, index);
        } else {
            // Unknown domain.
            throw new UserNotFoundException();
        }
    }
    
    // Store the salt and salted password so SCRAM-SHA-1 SASL auth can be used later.
    byte[] saltShaker = new byte[24];
    random.nextBytes(saltShaker);
    String salt = DatatypeConverter.printBase64Binary(saltShaker);

    
    final int iterations = ScramSha1SaslServer.ITERATION_COUNT.getValue();
    byte[] saltedPassword = null, clientKey = null, storedKey = null, serverKey = null;
try {
       saltedPassword = ScramUtils.createSaltedPassword(saltShaker, password, iterations);
           clientKey = ScramUtils.computeHmac(saltedPassword, "Client Key");
           storedKey = MessageDigest.getInstance("SHA-1").digest(clientKey);
           serverKey = ScramUtils.computeHmac(saltedPassword, "Server Key");
   } catch (SaslException | NoSuchAlgorithmException e) {
       Log.warn("Unable to persist values for SCRAM authentication.");
   }
   
    if (!scramOnly && !usePlainPassword) {
        try {
            encryptedPassword = AuthFactory.encryptPassword(password);
            // Set password to null so that it's inserted that way.
            password = null;
        }
        catch (UnsupportedOperationException uoe) {
            // Encryption may fail. In that case, ignore the error and
            // the plain password will be stored.
        }
    }
    if (scramOnly) {
        encryptedPassword = null;
        password = null;
    }

    Connection con = null;
    PreparedStatement pstmt = null;
    try {
        con = DbConnectionManager.getConnection();
        pstmt = con.prepareStatement(UPDATE_PASSWORD);
        if (password == null) {
            pstmt.setNull(1, Types.VARCHAR);
        }
        else {
            pstmt.setString(1, password);
        }
        if (encryptedPassword == null) {
            pstmt.setNull(2, Types.VARCHAR);
        }
        else {
            pstmt.setString(2, encryptedPassword);
        }
        if (storedKey == null) {
            pstmt.setNull(3, Types.VARCHAR);
        }
        else {
            pstmt.setString(3, DatatypeConverter.printBase64Binary(storedKey));
        }
        if (serverKey == null) {
            pstmt.setNull(4, Types.VARCHAR);
        }
        else {
            pstmt.setString(4, DatatypeConverter.printBase64Binary(serverKey));
        }
        pstmt.setString(5, salt);
        pstmt.setInt(6, iterations);
        pstmt.setString(7, username);
        pstmt.executeUpdate();
    }
    catch (SQLException sqle) {
        throw new UserNotFoundException(sqle);
    }
    finally {
        DbConnectionManager.closeConnection(pstmt, con);
    }
}
 
Example 17
Source File: SerializerUtils.java    From Cubert with Apache License 2.0 4 votes vote down vote up
public static String serializeToString(Object object) throws IOException
{
    byte[] bytes = serializeToBytes(object);

    return DatatypeConverter.printBase64Binary(bytes);
}
 
Example 18
Source File: TokenCreator.java    From cf-java-logging-support with Apache License 2.0 4 votes vote down vote up
/**
  * Run this application locally in order to generate valid dynamic log level
  * JWT tokens which enable you to change the log level threshold on your
  * CF-Application for a single thread.
  */
 public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchProviderException,
                                        DynamicLogLevelException, InvalidKeySpecException {

     /*
      * PLEASE PROVIDE THIS INFORMATION ***********************************
      */
     // Replace with email address
     String issuer = "[email protected]";
     // Replace with the log level that should be transmitted via the token
     // Valid log level thresholds are:
     // "TRACE", "DEBUG", "INFO", "WARN", "ERROR"
     String level = "TRACE";
     // Set a validity period in days
     long validityPeriodInDays = 2;
     // If available provide Base64 encoded private key here:
     String privateKey = "";
     // If available provide Base64 encoded private key here:
     String publicKey = "";
     // (If no keys are provided, new keys will be generated)
     /*
      * ********************************************************************
      */

     KeyPair keyPair;

     if (StringUtils.isNotBlank(privateKey)) {
         keyPair = new KeyPair(publicKeyConverter(publicKey), privateKeyConverter(privateKey));
     }

     else {
         KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(2048);
         keyPair = keyGen.generateKeyPair();
         // keyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair();
     }
     privateKey = DatatypeConverter.printBase64Binary(keyPair.getPrivate().getEncoded());
     publicKey = DatatypeConverter.printBase64Binary(keyPair.getPublic().getEncoded());
     Date issuedAt = new Date();
     Date expiresAt = new Date(new Date().getTime() + validityPeriodInDays * 86400000);
     String token = TokenCreator.createToken(keyPair, issuer, issuedAt, expiresAt, level);

     System.out.println("You successfully created a dynamic log level token with log level " + level + "!");
     System.out.println();
     System.out.println("Your private key is:");
     System.out.println(privateKey);
     System.out.println("Your public key is:");
     System.out.println(publicKey);
     System.out.println("Your JWT token with log level " + level + " is:");
     System.out.println(token);
     System.out.println();
     System.out.println("Please copy and save token and keys for later usage. The JWT token can now be written");
     System.out.println("to an HTTP header in order to change the corresponding request's log level to " + level);
     System.out.println("For token validation, the public key must be added to the environment of the application.");
     System.out.println("In order to generate a new token with specific keys, the variables privateKey and publicKey");
     System.out.println("can be instantiated with these keys");

 }
 
Example 19
Source File: Utils.java    From Doradus with Apache License 2.0 2 votes vote down vote up
/**
 * Convert the given String to UTF-8, encode the result with Base64, and return the
 * encoded value as a string. The result string will only contain valid Base64
 * characters.
 * 
 * @param   value   Unicode String value.
 * @return          Base64 encoding of UTF-8 encoded String value.
 */
public static String base64FromString(String value) {
    return DatatypeConverter.printBase64Binary(toBytes(value));
}
 
Example 20
Source File: Utils.java    From Doradus with Apache License 2.0 2 votes vote down vote up
/**
 * Convert (encode) the given binary value, beginning at the given offset and
 * consisting of the given length, using Base64.
 * 
 * @param  value                    A binary value.
 * @param  offset                   Zero-based index where data begins.
 * @param  length                   Number of bytes to encode.
 * @return                          Base64-encoded value.
 * @throws IllegalArgumentException If the given value is null.
 */
public static String base64FromBinary(byte[] value, int offset, int length) throws IllegalArgumentException {
    return DatatypeConverter.printBase64Binary(Arrays.copyOfRange(value, offset, offset + length));
}