/*
 * Class: RSAFormat
 *
 * Author: Alex Usun
 *
 * Date: 31/8/2005
 */
package com.jscape.inet.ssh.util.keyreader.openssh;

import com.jscape.inet.ssh.util.keyreader.KeyPairSpec;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;

/**
 * OpenSSH RSA key pair format.
 *
 * @author Alex Usun
 * @version 1.0
 * @see <a href="RSAFormat.java.html">Source code</a>
 */
public class RSAFormat
        extends OpenSSHFormat {

    private static final String ALGORITHM = "RSA";

    /**
     * @see OpenSSHFormat#getAlgorithm()
     */
    protected String getAlgorithm() {
        return ALGORITHM;
    }

    /**
     * @see OpenSSHFormat#restoreKeyPair(Record)
     */
    protected KeyPairSpec restoreKeyPair(Record record)
            throws IOException {
        DataReader bar = new DataReader(new ByteArrayInputStream(record.getKeyPairData()));

        bar.readByte(); // 0x30 SEQUENCE
        bar.readLength();
        bar.readByte(); // 0x02 INTEGER (version)
        bar.readBigInteger();
        bar.readByte(); // 0x02
        BigInteger modulus = bar.readBigInteger();
        bar.readByte();  // 0x02
        BigInteger publicExponent = bar.readBigInteger();
        bar.readByte();  // 0x02
        BigInteger privateExponent = bar.readBigInteger();

        return new KeyPairSpec(ALGORITHM, new RSAPublicKeySpec(modulus, publicExponent),
                               new RSAPrivateKeySpec(modulus, privateExponent));
    }


}
