NAME

Crypt::FNA - Fractal Numerical Algorithm with authenticated key exchange

VERSION

0.72

SYNOPSIS

use strict;
use warnings;
use Crypt::FNA 0.72;

# Bob. Keep $pending_b locally and send $offer to Alice.
my ($pending_b, $offer) = Crypt::FNA->start_exchange({
    private_key     => 'bob.pem',
    peer_public_key => 'alice.pub.pem',
    directions      => 16,
});

# Alice. Keep $pending_a locally and send $reply to Bob.
my ($pending_a, $reply) = Crypt::FNA->answer_exchange($offer, {
    private_key     => 'alice.pem',
    peer_public_key => 'bob.pub.pem',
});

# Bob sends $finish to Alice before sending application records.
my ($bob, $finish) = Crypt::FNA->finish_exchange($pending_b, $reply);
my $alice = Crypt::FNA->confirm_exchange($pending_a, $finish);

my $record = $bob->seal_message("Hello, Alice");
my $plain  = $alice->open_message($record);  # "Hello, Alice"
my $reply_record = $alice->seal_message("Hello, Bob");
my $reply_plain  = $bob->open_message($reply_record);

DESCRIPTION

The Fractal Numerical Algorithm (FNA) maps a byte to a point on a curve. The byte value determines how many segments to follow from the preceding point. The order of the initial directions determines the shape of the curve. The historical new interface lets callers set those directions and read or write the resulting coordinates.

Version 0.72 adds a way for two peers to agree on directions without sending the angles. Bob creates a fresh ML-KEM-768 key pair. Alice encapsulates a shared secret to Bob's public key and returns the capsule. Each side authenticates the exchange using a long-lived ML-DSA-65 identity. Both derive the same ordered list of directions and separate keys for confirmation and for authenticating records in each direction. Each peer contributes 32 bytes of fresh public salt to the exchange. Every session message also uses its own 16-byte random salt.

HANDSHAKE CLASS METHODS

The four methods below use the v2 wire format. Pass each message as one complete byte string. The application supplies transport and framing. Each peer keeps its private key and pending state locally. Authenticate the expected peer's public identity key before the first connection and again whenever that key changes.

start_exchange

my ($pending_b, $offer) = Crypt::FNA->start_exchange(\%options);

Called by Bob in list context. Generates a fresh ML-KEM-768 key pair, chooses the direction count and signs the offer with Bob's ML-DSA-65 private key. Send the 4,531-byte offer to Alice. The pending object holds Bob's private exchange state.

private_key

Required. Local filename of the caller's ML-DSA-65 private key in PEM format.

peer_public_key

Required. Local filename of the expected peer's verified ML-DSA-65 public key in PEM format. The two identities must be distinct.

passphrase

Optional. Passphrase for the local private PEM, as a byte string of up to 1,023 bytes without a NUL, carriage return or newline. An unencrypted PEM can be used without this option.

directions

Optional for Bob. An integer from 4 through 32. Omitting it draws the count uniformly from that interval. The signed offer discloses the count. The peers derive the ordered, distinct whole-degree angles locally.

answer_exchange

my ($pending_a, $reply) = Crypt::FNA->answer_exchange($offer, \%options);

Called by Alice in list context. Accepts private_key, peer_public_key and, when needed, passphrase. Verifies Bob's signature, validates his ephemeral public key, encapsulates a fresh shared secret and adds Alice's salt, signature and key confirmation. Send the 4,466-byte reply to Bob. Retain the pending object until Bob's final confirmation arrives.

finish_exchange

my ($bob, $finish) = Crypt::FNA->finish_exchange($pending_b, $reply);

Called by Bob in list context. Verifies Alice's signature, decapsulates the secret and checks her key confirmation. Returns Bob's session and a 37-byte final confirmation to send to Alice. Verifying a valid signature consumes Bob's pending state even if the subsequent key confirmation fails. Start a new exchange after such a failure.

confirm_exchange

my $alice = Crypt::FNA->confirm_exchange($pending_a, $finish);

Called by Alice. Verifies that Bob derived the expected confirmation key. On success, consumes Alice's pending state and returns her session. Only the handshake messages travel between the peers.

SESSION METHODS

finish_exchange and confirm_exchange return Crypt::FNA::Session objects. For textual data, encode to octets before sealing and decode after opening, for example with Encode.

direction_count

my $n = $session->direction_count;

Returns the negotiated number of FNA directions, an integer from 4 through 32.

seal_message

my $wire_record = $session->seal_message($octets);

Returns a binary record for the other peer. Accepts arbitrary bytes, including an empty string. Prepends a fresh 16-byte random salt, computes the FNA coordinates and verifies that the local decoder recovers the salt and every input byte. If rounded coordinates are ambiguous, retries with fresh salt. Throws an exception after eight unsuccessful attempts. Authenticates the record with the key for the sending direction.

open_message

my $octets = $session->open_message($wire_record);

Verifies the incoming record's HMAC before parsing its coordinates. Checks the recovered plaintext against a second tag, removes the salt and returns the original byte string. A peer's record must be opened with the receiving session for that exchange. Use an exception handler to distinguish failure from a valid empty message.

my $plain;
my $ok = eval { $plain = $session->open_message($record); 1 };
die "Record rejected: $@" unless $ok;

HISTORICAL FNA INTERFACE

new

my $fna = Crypt::FNA->new({
    angle  => [0, 60, -60, 0],
    r      => 7,
    square => 4096,
    magic  => 3,
    salted => 'true',
});

new() or new({}) uses the defaults below. An attribute accessor reads the current value without an argument and sets it when given an argument. Use identical geometry and salting settings for encryption and decryption.

angle

Ordered array reference of initial directions in decimal degrees. The default is [0, 60, -60, 0].

r and square

Curve order and side length of the square drawing area. The default order is 7 and the default side is 4,096. Both affect the segment length.

magic

Offset in the number of segments traversed for each byte. Use a digit from 1 through 9. The default is 3.

salted

Use the lowercase strings 'true' and 'false'. The historical default is 'false'. Setting 'true' adds magic ** 2 random decimal digits before processing the payload. Session methods always apply their own salt.

background and foreground

Three-element RGB array references, with components from 0 through 255. The defaults are white [255, 255, 255] and black [0, 0, 0].

message

Returns an array reference containing the historical validation and file diagnostics. Some successful operations leave an empty-string entry. A numeric zero is a diagnostic code. Filter by length to retain it.

my @codes = grep { defined($_) && length($_) } @{ $fna->message };

encrypt_file

$fna->encrypt_file($input_path, $coordinates_path);

Reads a non-empty input as bytes and writes two decimal coordinates per byte, one coordinate per line. Salting adds coordinate pairs for its prefix.

decrypt_file

$fna->decrypt_file($coordinates_path, $output_path);

Reconstructs bytes from a historical coordinate file using the same geometry and salting settings. Writes binary output. Use separate input and output paths for both file methods.

encrypt_scalar

my @coordinates = $fna->encrypt_scalar($octets);

Returns the coordinate list for a non-empty byte string. Capture the return value in list context.

decrypt_scalar

my $octets = $fna->decrypt_scalar(@coordinates);

Takes the flat coordinate list returned by encrypt_scalar and returns the recovered byte string.

mac

my $fingerprint = $fna->mac($input_path);

Computes the historical file fingerprint with salting disabled. The method uses Tie::File and writes a temporary coordinate file at the input path with the literal suffix fna appended. It overwrites that path and removes it on success. Choose an input path whose sibling is free. The fingerprint concatenates the last Y and X coordinates and strips decimal points and minus signs.

mac_scalar

my $fingerprint = $fna->mac_scalar($octets);

Computes the historical scalar fingerprint with salting disabled. It concatenates the last X and Y coordinates and removes decimal points. mac and mac_scalar use different serializations. Both are geometric fingerprints. Session integrity uses HMAC-SHA256.

make_fract

$fna->make_fract('koch', 1);     # writes koch.png

Draws the curve in PNG format using GD::Simple. Supply the filename without its extension and a positive zoom factor. Use 1 for the original scale. The image dimensions are square by square pixels.

GEOMETRY AND NUMERICAL CONVENTIONS

Let rho be the number of initial directions. Refining each segment into rho segments gives rho ** r segments at integer order r. For segment index k, the implementation computes the parent index and the position within that parent as follows.

g(k, rho) = int(k / rho)
p(k, rho) = k - rho * g(k, rho)

Each refinement adds the parent's heading and the heading at that position in the base. With the initial directions [0, 60, -60, 0], the four children of the 60-degree segment have headings [60, 120, 0, 60]. Curve drawing and byte encoding use this same indexing rule.

set_starting_angle saves the initial directions and converts the working angles to radians. init_geometry computes the starting coordinates and segment length. evaluate_this_angle combines the two headings. evaluate_this_coords advances the point using cosine and sine. crypt_fract walks a specified number of segments. calc_limit controls the historical angle cache. make_salt supplies the prefix when historical salting is enabled.

PI is 3.14159. doublePI is twice this value. The historical float constant is 5, the number of decimal places retained by round. Despite its name, round truncates toward zero. mod takes the signed remainder in radians relative to doublePI and truncates it to that precision. For example, Crypt::FNA::mod(-0.75) returns -0.75.

For an input byte of value b, the encoder walks b + magic + 1 segments from the preceding position and records the endpoint. The decoder follows the same path until the recorded coordinates match and recovers the byte from the number of steps. Distinct vertices can share rounded coordinates.

DIAGNOSTICS

The handshake and session methods throw exceptions for invalid arguments, unusable keys, failed signatures or confirmations, invalid records and OpenSSL errors. A pending object can be consumed only once.

Historical methods report the following diagnostic codes through message.

0          Invalid curve order
2          Invalid square side length
5          Invalid angle
7, 8       Cannot open encryption input or output
9, 10      Cannot open decryption input or output
11         Cannot write PNG output
12, 13     Invalid background RGB component or range
14, 15     Invalid foreground RGB component or range
16         GD::Simple could not be loaded
18         Invalid zoom
20, 21     Invalid magic or salted setting
22, 23     Tie::File unavailable or fingerprint input cannot be read

Earlier documentation also listed codes 1, 3, 6 and 19 for order, side length, angle notation and construction errors respectively. The current validator does not emit those codes.

REQUIREMENTS AND EXAMPLES

The exchange requires the openssl CLI, version 3.5 or later, with ML-KEM-768 and ML-DSA-65 enabled on a POSIX system providing /dev/stdin and /dev/stdout. Historical salted encryption uses openssl rand. The TCP examples also require IO::Socket::IP.

examples/alice.pl listens and examples/bob.pl connects. Their guide in examples/README.md shows how to create identities, verify the peer key and run both terminals. esempio_scambio.pl demonstrates both roles in one process. The Italian protocol description in Procedura_scambio_FNA_0.72.md specifies the handshake byte layout.

SECURITY CONSIDERATIONS

ML-KEM-768 and ML-DSA-65 are standardized primitives. The FNA handshake and geometric cipher are experimental. The confidentiality of FNA's coordinate stream has no established security proof. Record size reveals the payload length through the number of coordinate pairs. Session records carry authentication tags but have no built-in sequence counter. If order or replay matters, authenticate and check sequence numbers at the application layer, as the bundled chat does.

Version 0.72 requires v2 messages and ML-DSA-65 identity keys at both ends. Users of the 0.71 prototype must provision the new identity keys.

SEE ALSO

NIST FIPS 203 (ML-KEM), NIST FIPS 204 (ML-DSA) and RFC 5869 (HKDF).

Mario Rossano's original Italian article describes the construction of the FNA curve. http://www.perl.it/documenti/articoli/2010/04/anakryptfna.html.

AUTHOR AND SUPPORT

Mario Rossano (Anak), software@netlogica.it. Send bug reports to this address with the module, Perl and OpenSSL versions and a minimal example.

COPYRIGHT AND LICENSE

Copyright (C) 2009 Mario Rossano. Distributed under the Creative Commons Attribution-NonCommercial-ShareAlike 2.5 Italy license. For permissions beyond its scope, contact software@netlogicalab.com. https://creativecommons.org/licenses/by-nc-sa/2.5/it/.