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

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.KeyPair;
import java.security.spec.DSAPrivateKeySpec;
import java.security.spec.DSAPublicKeySpec;

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

    private static final String ALGORITHM = "DSA";
    private static final String SSH_ALGORITHM = "ssh-dss";

    protected KeyPair keyPairFor(byte[] publicKeyData, byte[] privateKeyData)
            throws Exception {
        DSAPublicKeySpec publicKeySpec = restorePublicKeySpec(publicKeyData);
        DSAPrivateKeySpec privateKeySpec = restorePrivateKeySpec(privateKeyData, publicKeySpec);

        return new KeyPairSpec(ALGORITHM, publicKeySpec, privateKeySpec).toKeyPair();
    }

    /**
     * @see PuttyFormat#sshAlgorithm()
     */
    protected String sshAlgorithm() {
        return SSH_ALGORITHM;
    }

    /**
     * Restores public key specification.
     *
     * @param data specification data
     *
     * @return restored specification
     *
     * @throws IOException if specification cannot be read
     */
    protected DSAPublicKeySpec restorePublicKeySpec(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 p = reader.readMpint();
        BigInteger q = reader.readMpint();
        BigInteger g = reader.readMpint();
        BigInteger y = reader.readMpint();

        return new DSAPublicKeySpec(y, p, q, g);
    }

    /**
     * Restores private key specification.
     *
     * @param data    specification data
     * @param publicKeySpec public key specification
     *
     * @return restored specification
     *
     * @throws IOException if specification cannot be read
     */
    protected DSAPrivateKeySpec restorePrivateKeySpec(byte[] data, DSAPublicKeySpec publicKeySpec)
            throws IOException {
        DataReader privateKeyReader = new DataReader(new ByteArrayInputStream(data));

        BigInteger x = privateKeyReader.readMpint();

        return new DSAPrivateKeySpec(x, publicKeySpec.getP(), publicKeySpec.getQ(), publicKeySpec.getG());
    }

}
