/*
 * Class: RSAFormat
 *
 * Author: Alex Usun
 *
 * Date: 1/9/2005
 */
package com.jscape.inet.ssh.util.keyreader.vandyke;

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

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

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

    private static final String ALGORITHM = "RSA";
    private static final String SSH_ALGORITHM = "ssh-rsa";

    /**
     * @see com.jscape.inet.ssh.util.keyreader.vandyke.VanDykeFormat#getAlgorithm()
     */
    protected String getAlgorithm() {
        return ALGORITHM;
    }

    /**
     * @see VanDykeFormat#restoreKeyPair(Record)
     */
    protected KeyPairSpec restoreKeyPair(Record record)
            throws IOException {
        RSAPublicKeySpec pubSpec = restorePublicKeySpec(record.getPublicKeyData());
        RSAPrivateKeySpec privSpec = restorePrivateKeySpec(record.getPrivateKeyData());

        return new KeyPairSpec(ALGORITHM, pubSpec, privSpec);
    }

    /**
     * Restores public key specification.
     *
     * @param data specification data
     *
     * @return restored specification
     *
     * @throws java.io.IOException if specification cannot be read
     */
    private RSAPublicKeySpec restorePublicKeySpec(byte[] data)
            throws IOException {
        DataReader publicKeyReader = new DataReader(new ByteArrayInputStream(data));

        String algorithm = publicKeyReader.readString();
        Assert.isTrue(SSH_ALGORITHM.equalsIgnoreCase(algorithm), "wrong key pair algorithm");

        BigInteger publicExponent = publicKeyReader.readMpint();
        BigInteger modulus = publicKeyReader.readMpint();

        return new RSAPublicKeySpec(modulus, publicExponent);
    }

    /**
     * Restores private key specification.
     *
     * @param data specification data
     *
     * @return restored specification
     *
     * @throws java.io.IOException if specification cannot be read
     */
    private RSAPrivateKeySpec restorePrivateKeySpec(byte[] data)
            throws IOException {
        DataReader reader = new DataReader(new ByteArrayInputStream(data));

        String algorithm = reader.readString();
        Assert.isTrue(SSH_ALGORITHM.equalsIgnoreCase(algorithm), "wrong key pair algorithm");

        BigInteger modulus = reader.readMpint();
        reader.readMpint(); // skip public exponent
        BigInteger privateExponent = reader.readMpint();

        return new RSAPrivateKeySpec(modulus, privateExponent);
    }

}
