Beispiel #1
0
  /**
   * @param <E> The generic entry type
   * @param entry The {@link PublicKeyEntry} whose contents are to be updated - ignored if {@code
   *     null}
   * @param data Assumed to contain at least {@code key-type base64-data} (anything beyond the
   *     BASE64 data is ignored) - ignored if {@code null}/empty
   * @return The updated entry instance
   * @throws IllegalArgumentException if bad format found
   */
  public static final <E extends PublicKeyEntry> E parsePublicKeyEntry(E entry, String data)
      throws IllegalArgumentException {
    if (GenericUtils.isEmpty(data) || (entry == null)) {
      return entry;
    }

    int startPos = data.indexOf(' ');
    if (startPos <= 0) {
      throw new IllegalArgumentException("Bad format (no key data delimiter): " + data);
    }

    int endPos = data.indexOf(' ', startPos + 1);
    if (endPos <= startPos) { // OK if no continuation beyond the BASE64 encoded data
      endPos = data.length();
    }

    String keyType = data.substring(0, startPos);
    String b64Data = data.substring(startPos + 1, endPos).trim();
    byte[] keyData = Base64.decodeString(b64Data);
    if (NumberUtils.isEmpty(keyData)) {
      throw new IllegalArgumentException("Bad format (no BASE64 key data): " + data);
    }

    entry.setKeyType(keyType);
    entry.setKeyData(keyData);
    return entry;
  }
Beispiel #2
0
 @Override
 public String toString() {
   byte[] data = getKeyData();
   return getKeyType()
       + " "
       + (NumberUtils.isEmpty(data) ? "<no-key>" : Base64.encodeToString(data));
 }
Beispiel #3
0
  /**
   * Encodes a public key data the same way as the {@link #parsePublicKeyEntry(String)} expects it
   *
   * @param <A> The generic appendable class
   * @param sb The {@link Appendable} instance to encode the data into
   * @param key The {@link PublicKey} - ignored if {@code null}
   * @return The updated appendable instance
   * @throws IOException If failed to append the data
   */
  public static <A extends Appendable> A appendPublicKeyEntry(A sb, PublicKey key)
      throws IOException {
    if (key == null) {
      return sb;
    }

    @SuppressWarnings("unchecked")
    PublicKeyEntryDecoder<PublicKey, ?> decoder =
        (PublicKeyEntryDecoder<PublicKey, ?>) KeyUtils.getPublicKeyEntryDecoder(key);
    if (decoder == null) {
      throw new StreamCorruptedException("Cannot retrieve decoder for key=" + key.getAlgorithm());
    }

    try (ByteArrayOutputStream s = new ByteArrayOutputStream(Byte.MAX_VALUE)) {
      String keyType = decoder.encodePublicKey(s, key);
      byte[] bytes = s.toByteArray();
      String b64Data = Base64.encodeToString(bytes);
      sb.append(keyType).append(' ').append(b64Data);
    }

    return sb;
  }