/*
 * Class: DSAFormat
 *
 * 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.DSAPrivateKeySpec;
import java.security.spec.DSAPublicKeySpec;

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

    private static final String ALGORITHM = "DSA";

    /**
     * @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 p = bar.readBigInteger();
        bar.readByte();  // 0x02
        BigInteger q = bar.readBigInteger();
        bar.readByte();  //0x02
        BigInteger g = bar.readBigInteger();
        bar.readByte();  // 0x02
        BigInteger y = bar.readBigInteger();
        bar.readByte();  //0x02
        BigInteger x = bar.readBigInteger();

        return new KeyPairSpec(ALGORITHM, new DSAPublicKeySpec(y, p, q, g),
                               new DSAPrivateKeySpec(x, p, q, g));
    }

}
