Java Code Examples for org.apache.solr.common.util.Base64#byteArrayToBase64()

The following examples show how to use org.apache.solr.common.util.Base64#byteArrayToBase64() . 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: CryptoKeys.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
/**
 * Initialize an RSA key pair from previously saved keys. The formats listed below have been tested, other formats may
 * also be acceptable but are not guaranteed to work.
 * @param privateKeyResourceName path to private key file, encoded as a PKCS#8 in a PEM file
 * @param publicKeyResourceName path to public key file, encoded as X509 in a DER file
 * @throws IOException if an I/O error occurs reading either key file
 * @throws InvalidKeySpecException if either key file is inappropriate for an RSA key
 */
public RSAKeyPair(URL privateKeyResourceName, URL publicKeyResourceName) throws IOException, InvalidKeySpecException {
  try (InputStream inPrivate = privateKeyResourceName.openStream()) {
    String privateString = new String(inPrivate.readAllBytes(), StandardCharsets.UTF_8)
        .replaceAll("-----(BEGIN|END) PRIVATE KEY-----", "");

    PKCS8EncodedKeySpec privateSpec = new PKCS8EncodedKeySpec(java.util.Base64.getMimeDecoder().decode(privateString));
    KeyFactory rsaFactory = KeyFactory.getInstance("RSA");
    privateKey = rsaFactory.generatePrivate(privateSpec);
  } catch (NoSuchAlgorithmException e) {
    throw new AssertionError("JVM spec is required to support RSA", e);
  }

  try (InputStream inPublic = publicKeyResourceName.openStream()) {
    publicKey = getX509PublicKey(inPublic.readAllBytes());
    pubKeyStr = Base64.byteArrayToBase64(publicKey.getEncoded());
  }
}
 
Example 2
Source File: InputFile.java    From ambari-logsearch with Apache License 2.0 5 votes vote down vote up
public BufferedReader openLogFile(File logFile) throws Exception {
  BufferedReader br = new BufferedReader(LogsearchReaderFactory.INSTANCE.getReader(logFile));
  fileKey = getFileKeyFromLogFile(logFile);
  base64FileKey = Base64.byteArrayToBase64(fileKey.toString().getBytes());
  logger.info("fileKey=" + fileKey + ", base64=" + base64FileKey + ". " + getShortDescription());
  return br;
}
 
Example 3
Source File: FieldType.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/**
 * Marshals a binary field value.
 */
protected static Object marshalBase64SortValue(Object value) {
  if (null == value) {
    return null;
  }
  final BytesRef val = (BytesRef)value;
  return Base64.byteArrayToBase64(val.bytes, val.offset, val.length);
}
 
Example 4
Source File: CryptoKeys.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/**
 * Create an RSA key pair with newly generated keys.
 */
public RSAKeyPair() {
  KeyPairGenerator keyGen;
  try {
    keyGen = KeyPairGenerator.getInstance("RSA");
  } catch (NoSuchAlgorithmException e) {
    throw new AssertionError("JVM spec is required to support RSA", e);
  }
  keyGen.initialize(DEFAULT_KEYPAIR_LENGTH);
  java.security.KeyPair keyPair = keyGen.genKeyPair();
  privateKey = keyPair.getPrivate();
  publicKey = keyPair.getPublic();
  pubKeyStr = Base64.byteArrayToBase64(publicKey.getEncoded());
}
 
Example 5
Source File: CursorMark.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/**
 * Generates a Base64 encoded serialized representation of the sort values 
 * encapsulated by this object, for use in cursor requests.
 *
 * @see #parseSerializedTotem
 */
public String getSerializedTotem() {
  if (null == this.values) {
    return CURSOR_MARK_START;
  }

  final List<SchemaField> schemaFields = sortSpec.getSchemaFields();
  final ArrayList<Object> marshalledValues = new ArrayList<>(values.size()+1);
  for (int i = 0; i < schemaFields.size(); i++) {
    SchemaField fld = schemaFields.get(i);
    Object safeValue = values.get(i);
    if (null != fld) {
      FieldType type = fld.getType();
      safeValue = type.marshalSortValue(safeValue);
    }
    marshalledValues.add(safeValue);
  }

  // TODO: we could also encode info about the SortSpec for error checking:
  // the type/name/dir from the SortFields (or a hashCode to act as a checksum) 
  // could help provide more validation beyond just the number of clauses.

  try (JavaBinCodec jbc = new JavaBinCodec(); ByteArrayOutputStream out = new ByteArrayOutputStream(256)) {
    jbc.marshal(marshalledValues, out);
    byte[] rawData = out.toByteArray();
    return Base64.byteArrayToBase64(rawData, 0, rawData.length);
  } catch (Exception ex) {
    throw new SolrException(ErrorCode.SERVER_ERROR,
                            "Unable to format search after totem", ex);
  }
}
 
Example 6
Source File: PKIAuthenticationPlugin.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@SuppressForbidden(reason = "Needs currentTimeMillis to set current time in header")
private Optional<String> generateToken() {
  SolrRequestInfo reqInfo = getRequestInfo();
  String usr;
  if (reqInfo != null) {
    Principal principal = reqInfo.getUserPrincipal();
    if (principal == null) {
      log.debug("generateToken: principal is null");
      //this had a request but not authenticated
      //so we don't not need to set a principal
      return Optional.empty();
    } else {
      usr = principal.getName();
    }
  } else {
    if (!isSolrThread()) {
      //if this is not running inside a Solr threadpool (as in testcases)
      // then no need to add any header
      log.debug("generateToken: not a solr (server) thread");
      return Optional.empty();
    }
    //this request seems to be originated from Solr itself
    usr = "$"; //special name to denote the user is the node itself
  }

  String s = usr + " " + System.currentTimeMillis();

  byte[] payload = s.getBytes(UTF_8);
  byte[] payloadCipher = publicKeyHandler.keyPair.encrypt(ByteBuffer.wrap(payload));
  String base64Cipher = Base64.byteArrayToBase64(payloadCipher);
  log.trace("generateToken: usr={} token={}", usr, base64Cipher);
  return Optional.of(base64Cipher);
}
 
Example 7
Source File: JWTAuthPlugin.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
protected String generateAuthDataHeader() {
  JWTIssuerConfig primaryIssuer = getPrimaryIssuer();
  Map<String,Object> data = new HashMap<>();
  data.put(JWTIssuerConfig.PARAM_AUTHORIZATION_ENDPOINT, primaryIssuer.getAuthorizationEndpoint());
  data.put("client_id", primaryIssuer.getClientId());
  data.put("scope", adminUiScope);
  data.put("redirect_uris", redirectUris);
  String headerJson = Utils.toJSONString(data);
  return Base64.byteArrayToBase64(headerJson.getBytes(StandardCharsets.UTF_8));
}
 
Example 8
Source File: HttpSolrClient.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private void setBasicAuthHeader(@SuppressWarnings({"rawtypes"})SolrRequest request, HttpRequestBase method) throws UnsupportedEncodingException {
  if (request.getBasicAuthUser() != null && request.getBasicAuthPassword() != null) {
    String userPass = request.getBasicAuthUser() + ":" + request.getBasicAuthPassword();
    String encoded = Base64.byteArrayToBase64(userPass.getBytes(FALLBACK_CHARSET));
    method.setHeader(new BasicHeader("Authorization", "Basic " + encoded));
  }
}
 
Example 9
Source File: Http2SolrClient.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private void setBasicAuthHeader(@SuppressWarnings({"rawtypes"})SolrRequest solrRequest, Request req) {
  if (solrRequest.getBasicAuthUser() != null && solrRequest.getBasicAuthPassword() != null) {
    String userPass = solrRequest.getBasicAuthUser() + ":" + solrRequest.getBasicAuthPassword();
    String encoded = Base64.byteArrayToBase64(userPass.getBytes(FALLBACK_CHARSET));
    req.header("Authorization", "Basic " + encoded);
  }
}
 
Example 10
Source File: FileCheckpointCleanupHelper.java    From ambari-logsearch with Apache License 2.0 5 votes vote down vote up
private static boolean wasFileRenamed(File folder, String searchFileBase64) {
  for (File file : folder.listFiles()) {
    Object fileKeyObj = FileUtil.getFileKey(file);
    String fileBase64 = Base64.byteArrayToBase64(fileKeyObj.toString().getBytes());
    if (searchFileBase64.equals(fileBase64)) {
      // even though the file name in the checkpoint file is different from the one it was renamed to, checkpoint files are
      // identified by their name, which is generated from the file key, which would be the same for the renamed file
      logger.info("CheckPoint clean: File key matches file " + file.getAbsolutePath() + ", it must have been renamed");
      return true;
    }
  }
  return false;
}
 
Example 11
Source File: InputSimulate.java    From ambari-logsearch with Apache License 2.0 5 votes vote down vote up
public String getBase64FileKey() {
  String fileKey;
  try {
    fileKey = InetAddress.getLocalHost().getHostAddress() + "|" + getFilePath();
  } catch (Exception e) {
    // skip
    fileKey = "localhost|" + getFilePath();
  }
  return Base64.byteArrayToBase64(fileKey.getBytes());
}
 
Example 12
Source File: SolrCloudAuthTestCase.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
protected static String makeBasicAuthHeader(String user, String pwd) {
  String userPass = user + ":" + pwd;
  return "Basic " + Base64.byteArrayToBase64(userPass.getBytes(UTF_8));
}
 
Example 13
Source File: ScipioHttpSolrClient.java    From scipio-erp with Apache License 2.0 4 votes vote down vote up
/**
 * Sets basic auth header to the given username and password.
 * <p>
 * DEV NOTE: Derived from <code>HttpSolrClient#setBasicAuthHeader</code>, which is private in superclass.
 */
protected void setBasicAuthHeader(HttpRequestBase method, String username, String password) throws UnsupportedEncodingException {
    String userPass = username + ":" + password;
    String encoded = Base64.byteArrayToBase64(userPass.getBytes(StandardCharsets.UTF_8));
    method.setHeader(new BasicHeader("Authorization", "Basic " + encoded));
}
 
Example 14
Source File: FileCheckpointCleanupHelper.java    From ambari-logsearch with Apache License 2.0 4 votes vote down vote up
private static boolean checkCheckPointFile(File checkPointFile) {
  boolean deleted = false;
  try (RandomAccessFile checkPointReader = new RandomAccessFile(checkPointFile, "r")) {
    int contentSize = checkPointReader.readInt();
    byte b[] = new byte[contentSize];
    int readSize = checkPointReader.read(b, 0, contentSize);
    if (readSize != contentSize) {
      logger.error("Couldn't read expected number of bytes from checkpoint file. expected=" + contentSize + ", read="
        + readSize + ", checkPointFile=" + checkPointFile);
    } else {
      String jsonCheckPointStr = new String(b, 0, readSize);
      Map<String, Object> jsonCheckPoint = LogFeederUtil.toJSONObject(jsonCheckPointStr);

      String logFilePath = (String) jsonCheckPoint.get("file_path");
      String logFileKey = (String) jsonCheckPoint.get("file_key");
      Integer maxAgeMin = null;
      if (jsonCheckPoint.containsKey("max_age_min")) {
        maxAgeMin = Integer.parseInt(jsonCheckPoint.get("max_age_min").toString());
      }
      if (logFilePath != null && logFileKey != null) {
        boolean deleteCheckPointFile = false;
        File logFile = new File(logFilePath);
        if (logFile.exists()) {
          Object fileKeyObj = FileUtil.getFileKey(logFile);
          String fileBase64 = Base64.byteArrayToBase64(fileKeyObj.toString().getBytes());
          if (!logFileKey.equals(fileBase64)) {
            logger.info("CheckPoint clean: File key has changed. old=" + logFileKey + ", new=" + fileBase64 + ", filePath=" +
              logFilePath + ", checkPointFile=" + checkPointFile.getAbsolutePath());
            deleteCheckPointFile = !wasFileRenamed(logFile.getParentFile(), logFileKey);
          } else if (maxAgeMin != null && maxAgeMin != 0 && FileUtil.isFileTooOld(logFile, maxAgeMin)) {
            deleteCheckPointFile = true;
            logger.info("Checkpoint clean: File reached max age minutes (" + maxAgeMin + "):" + logFilePath);
          }
        } else {
          logger.info("CheckPoint clean: Log file doesn't exist. filePath=" + logFilePath + ", checkPointFile=" +
            checkPointFile.getAbsolutePath());
          deleteCheckPointFile = !wasFileRenamed(logFile.getParentFile(), logFileKey);
        }
        if (deleteCheckPointFile) {
          logger.info("Deleting CheckPoint file=" + checkPointFile.getAbsolutePath() + ", logFile=" + logFilePath);
          checkPointFile.delete();
          deleted = true;
        }
      }
    }
  } catch (EOFException eof) {
    logger.warn("Caught EOFException. Ignoring reading existing checkPoint file. " + checkPointFile);
  } catch (Throwable t) {
    logger.error("Error while checking checkPoint file. " + checkPointFile, t);
  }

  return deleted;
}
 
Example 15
Source File: BinaryField.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
private String toBase64String(ByteBuffer buf) {
  return Base64.byteArrayToBase64(buf.array(), buf.position(), buf.limit()-buf.position());
}
 
Example 16
Source File: BasicAuthStandaloneTest.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
public static void setBasicAuthHeader(AbstractHttpMessage httpMsg, String user, String pwd) {
  String userPass = user + ":" + pwd;
  String encoded = Base64.byteArrayToBase64(userPass.getBytes(UTF_8));
  httpMsg.setHeader(new BasicHeader("Authorization", "Basic " + encoded));
  log.info("Added Basic Auth security Header {}",encoded );
}
 
Example 17
Source File: BinaryDocValuesField.java    From liresolr with GNU General Public License v2.0 4 votes vote down vote up
private String toBase64String(ByteBuffer buf) {
    return Base64.byteArrayToBase64(buf.array(), buf.position(), buf.limit() - buf.position());
}