All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.spotify.crtauth.agentsigner.RSA Maven / Gradle / Ivy

Go to download

An implementation of the Signer interface in crtauth-java that connects to the local ssh-agent.

The newest version!
/**
 * Copyright (c) 2015 Spotify AB.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.spotify.crtauth.agentsigner;

import com.google.common.base.Objects;

import com.spotify.crtauth.exceptions.CrtAuthException;
import com.spotify.crtauth.utils.TraditionalKeyParser;

import org.apache.commons.codec.binary.Base64;

import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.RSAPublicKeySpec;
import java.util.Iterator;

class RSA {

  static final String RSA_LABEL = "ssh-rsa";

  private RSA() {
  }

  /**
   * Create an {@link RSAPublicKey} from bytes.
   * @param key Array of bytes representing RSA public key.
   * @return {@link RSAPublicKey}
   * @throws CrtAuthException
   * @throws InvalidKeyException
   * @throws NoSuchAlgorithmException
   * @throws InvalidKeySpecException
   */
  static RSAPublicKey from(final byte[] key)
      throws CrtAuthException, InvalidKeyException, NoSuchAlgorithmException,
             InvalidKeySpecException {

    final String s = new String(key);
    final byte[] encoded;
    final String decoded;
    if (s.startsWith(RSA_LABEL)) {
      decoded = s.split(" ")[1];
      encoded = Base64.decodeBase64(decoded);
    } else {
      encoded = key;
      decoded = Base64.encodeBase64String(key);
    }

    final Iterator fields = new ByteIterator(encoded);
    final String sigType = new String(fields.next());
    if (!sigType.equals(RSA_LABEL)) {
      throw new CrtAuthException(String.format(
          "Unknown key type %s. This code currently only supports %s.", sigType, RSA_LABEL));
    }

    final RSAPublicKeySpec keySpec =
        TraditionalKeyParser.parsePemPublicKey(RSA_LABEL + " " + decoded + " ");
    final KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    return (RSAPublicKey) keyFactory.generatePublic(keySpec);
  }

  @Override
  public String toString() {
    return Objects.toStringHelper(this)
        .toString();
  }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy