package Passwd::Keyring::OSXKeychain::PasswordTranslate;

use warnings;
use strict;
use base 'Exporter';
our @EXPORT_OK = qw(read_security_encoded_passwd);

use Encode;

=head1 NAME

Passwd::Keyring::OSXKeychain::PasswordTranslate

=head1 DESCRIPTION

Helper routines, responsible for encoding and decoding passwords from
MacOS/X security escaped forms. Used internally inside Passwd::Keyring::OSXKeychain.

=head2 read_security_encoded_passwd

Tries to decode password given by security -w, handling known escaping schemes.

=cut

sub read_security_encoded_passwd {
    my ($encoded_password) = @_;

    if($encoded_password =~ /^(?:[0-9a-f][0-9a-f])+$/i) {
        my $binary = pack('H*', $encoded_password);
        $binary =~ s{\xFF{3}}{}g;
        my $text = decode_utf8($binary);
        return $text;
    } 

    # By default we assume plain text
    return $encoded_password;
}




1;
