int write_data(const char *filename, char *out, int len, unsigned char *key)
{
    int total, written;
    BIO *cipher, *b64, *buffer, *file;
 
    /* obt@t@CBIOݗpɍ쐬 */
    file = BIO_new_file(filename, "w");
    if (!file)
        return 0;
 
    /* t@Cւ݂̏̃obt@ƂāAobt@p̃tB^BIO쐬 */
    buffer = BIO_new(BIO_f_buffer());
 
    /* Base64p̃tB^BIO쐬 */
    b64 = BIO_new(BIO_f_base64());
 
    /* Íp̃tB^BIO쐬ݒ
       BIO_set_cipher̍Ō̈́AÍ̏ꍇ1Ȁꍇ0 */
    cipher = BIO_new(BIO_f_cipher());
    BIO_set_cipher(cipher, EVP_des_ede3_cbc(), key, NULL, 1);
 
    /* BIO`F[̏Ԃɕׂ
       cipher-b64-buffer-file */
    BIO_push(cipher, b64);
    BIO_push(b64, buffer);
    BIO_push(buffer, file);
 
    /* f[^t@Cɏރ[v
       bƂȂt@CubLOƌȂăG[`FbN */
    for (total = 0;  total < len;  total += written)
    {
        if ((written = BIO_write(cipher, out + total, len - total)) <= 0)
        {
            if (BIO_should_retry(cipher))
            {
                written = 0;
                continue;
            }
            break;
        }
    }
 
    /* ׂẴf[^Ƃ肠t@CɊi[ꂽƂmF */
    BIO_flush(cipher);
 
    /* ŁABIO_free_all(cipher)ĂяoBIO`F[
       ł̓fƂāAŏb64`F[͂ */
    BIO_pop(b64);
 
    /* ̎_łb64ptB^BIO؂藣Ă
       `F[́AÍptB^BIO-obt@ptB^BIO-obt@t@CBIȌ
       ȉɂAׂẴ */
    BIO_free(b64);
    BIO_free_all(cipher);
}
