use {crate::Error, simple_asn1::ASN1Block};

/// Encode an RSA private key with PKCS#1
pub fn private_key(key: &rsa::RSAPrivateKey) -> Result<Vec<u8>, Error> {
    let encoded_key = crate::pkcs1::private_key(key)?;

    let mut data = Vec::new();

    data.push(ASN1Block::Integer(0, simple_asn1::BigInt::default()));
    data.push(ASN1Block::Sequence(
        0,
        vec![ASN1Block::ObjectIdentifier(0, crate::rsa_oid())],
    ));
    data.push(ASN1Block::OctetString(0, encoded_key));

    simple_asn1::to_der(&ASN1Block::Sequence(0, data)).map_err(Into::into)
}

/// Encode an RSA public key with PKCS#1
pub fn public_key(key: &rsa::RSAPublicKey) -> Result<Vec<u8>, Error> {
    let pkcs1_public_key = crate::pkcs1::public_key(key)?;

    let mut data = Vec::new();

    data.push(ASN1Block::Sequence(
        0,
        vec![ASN1Block::ObjectIdentifier(0, crate::rsa_oid())],
    ));
    data.push(ASN1Block::BitString(
        0,
        pkcs1_public_key.len() * 8,
        pkcs1_public_key,
    ));

    simple_asn1::to_der(&ASN1Block::Sequence(0, data)).map_err(Into::into)
}
