2010-08-20 3 views
12

Come è possibile utilizzare una voce dal file di sistema authorized_keys per un'implementazione java.security.PublicKey? Voglio specificamente confrontare una chiave pubblica dal file authorized_keys con una chiave pubblica disponibile nell'interfaccia Apache SSHD PublickeyAuthenticator.Utilizzo della chiave pubblica da authorized_keys con sicurezza Java

+0

Potreste anche voler chiedere questo sulla mailing list Mina. Questa è una domanda molto buona, in quanto questo è uno dei pochi componenti mancanti per un'implementazione sshd Java sicura. –

risposta

16

Sono rimasto sorpreso perché non c'è niente di evidente in questo. Sono curioso e ho implementato un modo per decodificare i file authorized_keys. Questo dipende da Apache Commons Codec per la decodifica Base64.

import java.io.File; 
import java.math.BigInteger; 
import java.security.KeyFactory; 
import java.security.PublicKey; 
import java.security.spec.DSAPublicKeySpec; 
import java.security.spec.RSAPublicKeySpec; 
import java.util.Scanner; 

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

public class AuthorizedKeysDecoder { 
    private byte[] bytes; 
    private int pos; 

    public PublicKey decodePublicKey(String keyLine) throws Exception { 
     bytes = null; 
     pos = 0; 

     // look for the Base64 encoded part of the line to decode 
     // both ssh-rsa and ssh-dss begin with "AAAA" due to the length bytes 
     for (String part : keyLine.split(" ")) { 
      if (part.startsWith("AAAA")) { 
       bytes = Base64.decodeBase64(part); 
       break; 
      } 
     } 
     if (bytes == null) { 
      throw new IllegalArgumentException("no Base64 part to decode"); 
     } 

     String type = decodeType(); 
     if (type.equals("ssh-rsa")) { 
      BigInteger e = decodeBigInt(); 
      BigInteger m = decodeBigInt(); 
      RSAPublicKeySpec spec = new RSAPublicKeySpec(m, e); 
      return KeyFactory.getInstance("RSA").generatePublic(spec); 
     } else if (type.equals("ssh-dss")) { 
      BigInteger p = decodeBigInt(); 
      BigInteger q = decodeBigInt(); 
      BigInteger g = decodeBigInt(); 
      BigInteger y = decodeBigInt(); 
      DSAPublicKeySpec spec = new DSAPublicKeySpec(y, p, q, g); 
      return KeyFactory.getInstance("DSA").generatePublic(spec); 
     } else { 
      throw new IllegalArgumentException("unknown type " + type); 
     } 
    } 

    private String decodeType() { 
     int len = decodeInt(); 
     String type = new String(bytes, pos, len); 
     pos += len; 
     return type; 
    } 

    private int decodeInt() { 
     return ((bytes[pos++] & 0xFF) << 24) | ((bytes[pos++] & 0xFF) << 16) 
       | ((bytes[pos++] & 0xFF) << 8) | (bytes[pos++] & 0xFF); 
    } 

    private BigInteger decodeBigInt() { 
     int len = decodeInt(); 
     byte[] bigIntBytes = new byte[len]; 
     System.arraycopy(bytes, pos, bigIntBytes, 0, len); 
     pos += len; 
     return new BigInteger(bigIntBytes); 
    } 

    public static void main(String[] args) throws Exception { 
     AuthorizedKeysDecoder decoder = new AuthorizedKeysDecoder(); 
     File file = new File("authorized_keys"); 
     Scanner scanner = new Scanner(file).useDelimiter("\n"); 
     while (scanner.hasNext()) { 
      System.out.println(decoder.decodePublicKey(scanner.next())); 
     } 
     scanner.close(); 
    } 
} 
+3

Non è necessario aggiungere la libreria di comuni come dipendenza solo per quello. Date un'occhiata a DatatypeConverter # parseBase64Binary http://docs.oracle.com/javase/7/docs/api/javax/xml/bind/DatatypeConverter.html#parseBase64Binary(java.lang.String) – LanguagesNamedAfterCofee

+0

Grazie, amico! Mi ha risparmiato ore di lavoro. –

+0

Darei 5 ups se possibile! Grazie mille per questo! – Daniel

2

Per WhiteFang34,

Il codice è impressionante e utile anche per me, ma ha un piccolo bug. Il metodo Base64.decodeBase64 riceve solo array di byte. Quindi ho risolto così.

for (String part : keyLine.split(" ")) { 
     if (part.startsWith("AAAA")) { 
      byte [] bytePart = part.getBytes(); 
      bytes = Base64.decodeBase64(bytePart); 
      break; 
     } 
    } 

In ogni caso, grazie per aver scritto il codice. Spero che tu carichi questo codice su github o altrove, o per consentirmi di caricarlo nei miei repository github.

+0

Sembra che dipenda da quale classe Base64' stai usando. Quello incluso in Commons Codec 1.4 e versioni successive ha il metodo che ho usato: ['decodeBase64 (java.lang.String)'] (http://commons.apache.org/codec/api-release/org/apache/commons/ codec/binary/Base64.html # decodeBase64 (java.lang.String)) – WhiteFang34

5

Se si vuole invertire il processo, vale a dire codificare un oggetto Java PublicKey in un formato voce per Linux authorized_keys, si può usare questo codice:

/** 
    * Encode PublicKey (DSA or RSA encoded) to authorized_keys like string 
    * 
    * @param publicKey DSA or RSA encoded 
    * @param user username for output authorized_keys like string 
    * @return authorized_keys like string 
    * @throws IOException 
    */ 
    public static String encodePublicKey(PublicKey publicKey, String user) 
      throws IOException { 
     String publicKeyEncoded; 
     if(publicKey.getAlgorithm().equals("RSA")){ 
      RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey; 
      ByteArrayOutputStream byteOs = new ByteArrayOutputStream(); 
      DataOutputStream dos = new DataOutputStream(byteOs); 
      dos.writeInt("ssh-rsa".getBytes().length); 
      dos.write("ssh-rsa".getBytes()); 
      dos.writeInt(rsaPublicKey.getPublicExponent().toByteArray().length); 
      dos.write(rsaPublicKey.getPublicExponent().toByteArray()); 
      dos.writeInt(rsaPublicKey.getModulus().toByteArray().length); 
      dos.write(rsaPublicKey.getModulus().toByteArray()); 
      publicKeyEncoded = new String(
        Base64.encodeBase64(byteOs.toByteArray())); 
      return "ssh-rsa " + publicKeyEncoded + " " + user; 
     } 
     else if(publicKey.getAlgorithm().equals("DSA")){ 
      DSAPublicKey dsaPublicKey = (DSAPublicKey) publicKey; 
      DSAParams dsaParams = dsaPublicKey.getParams(); 

      ByteArrayOutputStream byteOs = new ByteArrayOutputStream(); 
      DataOutputStream dos = new DataOutputStream(byteOs); 
      dos.writeInt("ssh-dss".getBytes().length); 
      dos.write("ssh-dss".getBytes()); 
      dos.writeInt(dsaParams.getP().toByteArray().length); 
      dos.write(dsaParams.getP().toByteArray()); 
      dos.writeInt(dsaParams.getQ().toByteArray().length); 
      dos.write(dsaParams.getQ().toByteArray()); 
      dos.writeInt(dsaParams.getG().toByteArray().length); 
      dos.write(dsaParams.getG().toByteArray()); 
      dos.writeInt(dsaPublicKey.getY().toByteArray().length); 
      dos.write(dsaPublicKey.getY().toByteArray()); 
      publicKeyEncoded = new String(
        Base64.encodeBase64(byteOs.toByteArray())); 
      return "ssh-dss " + publicKeyEncoded + " " + user; 
     } 
     else{ 
      throw new IllegalArgumentException(
        "Unknown public key encoding: " + publicKey.getAlgorithm()); 
     } 
    } 
2

La stessa soluzione, ma delega il decodeInt() per la DataInputStream. Rimuovo dal codice originale BouncyCastleProvider per KeyFactory non appena conosce già l'algoritmo RSA.

Fonte originale: https://github.com/ragnar-johannsson/CloudStack/blob/master/utils/src/com/cloud/utils/crypt/RSAHelper.java

private static RSAPublicKey readKey(String key) throws Exception { 
    // key = "ssh-rsa <myBase64key> <email>" 
    byte[] encKey = Base64.decodeBase64(key.split(" ")[1]); 
    DataInputStream dis = new DataInputStream(new ByteArrayInputStream(encKey)); 

    byte[] header = readElement(dis); 
    String pubKeyFormat = new String(header); 
    if (!pubKeyFormat.equals("ssh-rsa")) 
    throw new RuntimeException("Unsupported format"); 

    byte[] publicExponent = readElement(dis); 
    byte[] modulus = readElement(dis); 

    KeySpec spec = new RSAPublicKeySpec(new BigInteger(modulus), new BigInteger(publicExponent)); 
    KeyFactory keyFactory = KeyFactory.getInstance("RSA"); 
    RSAPublicKey pubKey = (RSAPublicKey) keyFactory.generatePublic(spec); 

    return pubKey; 
} 

private static byte[] readElement(DataInput dis) throws IOException { 
    int len = dis.readInt(); 
    byte[] buf = new byte[len]; 
    dis.readFully(buf); 
    return buf; 
} 
+0

GRAZIE! Dopo ore di battute contro questo, il tuo codice aveva senso per me e ha risolto il problema! Ottima idea con il metodo 'readElement'. – CullenJ