Foros del Web

Foros del Web (http://www.forosdelweb.com/)
-   .NET (http://www.forosdelweb.com/f29/)
-   -   Ayuda sobre codigo en Perl (http://www.forosdelweb.com/f29/ayuda-sobre-codigo-perl-320226/)

Nombela 27/07/2005 04:32

Ayuda sobre codigo en Perl
 
Estoy intentado crear una funcion en .net que me emule esta de perl:

if (!$Password) {
print STDERR "Usage: bin/CryptPassword.pl NEWPW\n";
}
else {
my $Length = length($Password)*8;
chomp $Password;
# get bit code
my $T = unpack("B$Length", $Password);
# crypt bit code
$T =~ s/1/A/g;
$T =~ s/0/1/g;
$T =~ s/A/0/g;
# get ascii code
$T = pack("B$Length", $T);
# get hex code
my $H = unpack("h$Length", $T);
print "Crypted password: {$H}\n";
}

Alguien que pudiera echarme un cable xq no veo donde le pasa el valor del password que mete el usuario.


gracias.

chcma 27/07/2005 04:41

mmm, creo que .NET soporta perl, ¿No?

Nombela 27/07/2005 05:45

no lo se pero seria cojonudo la verdad

chcma 27/07/2005 09:47

http://aspn.activestate.com/ASPN/NET

http://aspn.activestate.com/ASPN/Downloads/PerlASPX/

Nombela 28/07/2005 01:02

Gracias pero por lo que veo el control es de pago y yo solo kiero usar esa funcion d perl para poder meter los password en mi base de datos encryptados de esa forma.
Alguien que me echara una mano???

gracie

Nombela 29/07/2005 09:38

Nadie sabe un poquito de Perl que me pueda echar una mano???

gracias

Nombela 17/08/2005 03:22

Help Please!!!
 
Help Please!!!

xknown 17/08/2005 11:18

Aquí lo hice como prueba de concepto, pruébalo, haber si lo logré o no :p
Código:

using System;

public class Bar
{
        public static void Main(string[] args)
        {
                string password = Console.ReadLine();
                Console.WriteLine(encrypt(password.Trim()));
        }
        public static string encrypt(string password)
        {
                string result="";
                foreach (char c in password.ToCharArray())
                        result += encode(c);
                return result;
        }
        public static string encode(char mychar)
        {
                int result = (int) mychar;
                result = (~result) & 255;                       
                result = (result & 15)<<4 | (result & 240)>>4;                       
                return string.Format("{0:x}", result);
        }
}

Saludos
PS. Esa codificación es muy simple, creo deberías usar algo más seguro

Nombela 18/08/2005 01:41

No me sale igual
 
Lo primero gracias por la ayuda, he probado la codificacion ke me pusiste y no me saca el mismo resultado que la echa en Perl.
AL meter de contraseña cgr, deberia sacarme prjqSmRFQBP7c y en lugar de eso me saca c989d8.

La seguridad que yo utilizo en mi aplicacion es md5 pero esto es para poder integrar en mi programa otra aplicacion echa en perl.


gracias.

xknown 18/08/2005 13:06

Estas seguro(a) que pusiste el código correcto, porque a mi me devuelve la misma cosa..., es más puse el código en esta dirección (el parámetro pwd indica la cadena a encriptar):
http://buayacorp.com/cgi-bin/foo.pl?pwd=cgr

El código de dicho script es el siguiente (no hice ningún cambio notorio al script que muestras arriba):
Código:

#!/usr/local/bin/perl

use CGI qw(:standard);
$Password = param('pwd');

my $Length = length($Password)*8;
chomp $Password;
# get bit code
my $T = unpack("B$Length", $Password);
# crypt bit code
$T =~ s/1/A/g;
$T =~ s/0/1/g;
$T =~ s/A/0/g;
# get ascii code
$T = pack("B$Length", $T);
# get hex code
my $H = unpack("h$Length", $T);
#print "Crypted password: {$H}\n";

print <<END;
Content-Type: text/html; charset=iso-8859-1

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<p>Encriptado: $H</p>
END

Saludos

Nombela 19/08/2005 01:50

Este es el codigo completo del CryptPassword.pl:

#!/usr/bin/perl -w
# --
# bin/CryptPassword.pl - to crypt database password for Kernel/Config.pm
# Copyright (C) 2001-2004 Martin Edenhofer <[email protected]>
# --
# $Id: CryptPassword.pl,v 1.1 2004/06/22 08:01:28 martin Exp $
# --
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
# --

use strict;

use vars qw($VERSION);
$VERSION = '$Revision: 1.1 $';
$VERSION =~ s/^\$.*:\W(.*)\W.+?$/$1/;

# --
# check args
# --
my $Password = shift;
print "bin/CryptPassword.pl <Revision $VERSION> - to crypt database password for Kernel/Config.pm\n";
print "Copyright (c) 2001-2004 Martin Edenhofer <martin\@otrs.org>\n";

if (!$Password) {
print STDERR "Usage: bin/CryptPassword.pl NEWPW\n";
}
else {
my $Length = length($Password)*8;
chomp $Password;
# get bit code
my $T = unpack("B$Length", $Password);
# crypt bit code
$T =~ s/1/A/g;
$T =~ s/0/1/g;
$T =~ s/A/0/g;
# get ascii code
$T = pack("B$Length", $T);
# get hex code
my $H = unpack("h$Length", $T);
print "Crypted password: {$H}\n";
}


Yo creo que es lo mismo que te puse. El problema es que el programa que intento integrar en mi aplicacion y que esta hecho en PERL en la base de datos mete prjqSmRFQBP7c. Y no se como hace para sacar ese resultado.

gracias

xknown 19/08/2005 13:05

Dime una cosa, estás probando el script que pusiste para generar esa cadena? o utilizas el programa al que haces mención, para hacerlo.

En mi opinión hay algún proceso más que se realiza dentro de tu programa, porque el script que pones, no puede generar la cadena que me muestras para "cgr"...

Saludos

Nombela 22/08/2005 02:07

estoy probando el programa ke se usa para hacerlo asi ke seguramente tengas razon y ademas del script ese, use otro proceso para encryptar. Y es ke de perl no tengo ni idea.

Te pongo aqui unos archivos que saco de la aplicacion de perl por si viniera algo que interesara, xq yo no lo entiendo.

# --
# Kernel/Config.pm - Config file for OTRS kernel
# Copyright (C) 2001-2004 Martin Edenhofer <[email protected]>
# --
# $Id: Config.pm.dist,v 1.13 2004/08/10 06:56:39 martin Exp $
# --
# This software comes with ABSOLUTELY NO WARRANTY. For details, see
# the enclosed file COPYING for license information (GPL). If you
# did not receive this file, see http://www.gnu.org/licenses/gpl.txt.
# --
# Note:
#
# -->> OTRS does have a lot of config settings. For more settings
# (Notifications, TicketViewAccelerator, TicketNumberGenerator,
# LDAP, PostMaster, Session, Preferences, ...) see
# Kernel/Config/Defaults.pm and copy your wanted lines into "this"
# config file. This file will not be changed on update!
#
# --
package Kernel::Config;
# --
sub Load {
my $Self = shift;
# ---------------------------------------------------- #
# ---------------------------------------------------- #
# #
# Start of your own config options!!! #
# #
# ---------------------------------------------------- #
# ---------------------------------------------------- #

# ---------------------------------------------------- #
# system data #
# ---------------------------------------------------- #
# SecureMode
# (Enable this so you can't use the installer.pl)
$Self->{SecureMode} = 0;
# SystemID
# (The identify of the system. Each ticket number and
# each http session id starts with this number)
$Self->{SystemID} = 10;
# TicketHook
# (To set the Ticket identifier. Some people want to
# set this to e. g. 'Call#', 'MyTicket#' or 'TN'.)
$Self->{TicketHook} = 'Ticket#';
# FQDN
# (Full qualified domain name of your system.)
$Self->{FQDN} = 'yourhost.example.com';
# AdminEmail
# (Email of the system admin.)
$Self->{AdminEmail} = '[email protected]';
# Organization
# (If this is anything other than '', then the email will have an
# Organization X-Header)
$Self->{Organization} = 'Example Company';

# ---------------------------------------------------- #
# database settings #
# ---------------------------------------------------- #
# DatabaseHost
# (The database host.)
$Self->{DatabaseHost} = 'localhost';
# Database
# (The database name.)
$Self->{Database} = 'otrs';
# DatabaseUser
# (The database user.)
$Self->{DatabaseUser} = 'otrs';
# DatabasePw
# (The password of database user. You also can use bin/CryptPassword.pl
# for crypted passwords.)
$Self->{DatabasePw} = 'some-pass';
# DatabaseDSN
# (The database DSN for MySQL ==> more: "man DBD::mysql")
$Self->{DatabaseDSN} = "DBI:mysql:database=$Self->{Database};host=$Self->{DatabaseHost};";

# (The database DSN for PostgrSQL ==> more: "man DBD::Pg")
# $Self->{DatabaseDSN} = "DBI:Pg:dbname=$Self->{Database};";

# ---------------------------------------------------- #
# fs root directory
# ---------------------------------------------------- #
$Self->{Home} = '/opt/otrs';

# ************************************************** ** #
# insert your own config settings "here" #
# config settings taken from Kernel/Config/Defaults.pm #
# ************************************************** ** #
# $Self->{SessionUseCookie} = 0;
# $Self->{CheckMXRecord} = 0;

# ************************************************** ** #

# ---------------------------------------------------- #
# data inserted by installer #
# ---------------------------------------------------- #
# $DIBI$

# ---------------------------------------------------- #
# ---------------------------------------------------- #
# #
# End of your own config options!!! #
# #
# ---------------------------------------------------- #
# ---------------------------------------------------- #
}

# ---------------------------------------------------- #
# needed system stuff (don't edit this) #
# ---------------------------------------------------- #
use strict;
use vars qw(@ISA $VERSION);
use Kernel::Config::Defaults;
push (@ISA, 'Kernel::Config::Defaults');
$VERSION = '$Revision: 1.13 $';
$VERSION =~ s/^\$.*:\W(.*)\W.+?$/$1/;
# -----------------------------------------------------#

1;

Nombela 22/08/2005 02:09

y otro archivo: otrs.setPassword

#!/usr/bin/perl -w
# --
# otrs.setPassword - Changes or Sets password for a user
# Copyright (C) 2002 Atif Ghaffar <[email protected]>
# $Id: otrs.setPassword,v 1.7 2003/01/23 22:50:09 martin Exp $
# This software comes with ABSOLUTELY NO WARRANTY. For details, see
# the enclosed file COPYING for license information (GPL). If you
# did not receive this file, see http://www.gnu.org/licenses/gpl.txt.
# --

use File::Basename;
use FindBin qw($RealBin);
use lib dirname($RealBin);
use lib dirname($RealBin)."/Kernel/cpan-lib";

unless ($ARGV[1]){
print "$FindBin::Script username password";
print "\n";
exit;
}

use strict;
use Kernel::Config;
use Kernel::System::Log;
use Kernel::System::DB;
use Kernel::System::User;

# --
# create common objects
# --
my %CommonObject = ();
$CommonObject{ConfigObject} = Kernel::Config->new(%CommonObject);
$CommonObject{LogObject} = Kernel::System::Log->new(%CommonObject, LogPrefix => 'otrs.setPassword');
$CommonObject{DBObject} = Kernel::System::DB->new(%CommonObject);
$CommonObject{UserObject} = Kernel::System::User->new(%CommonObject);



my %Param;
undef %Param;

# user id of the person Changing the record
$Param{UserID}='1';

$Param{UserLogin}=$ARGV[0];
$Param{PW}=$ARGV[1];


$CommonObject{UserObject}->SetPassword(%Param);

# --
exit (0);

Nombela 22/08/2005 02:18

y esto forma parte del archivo donde se loga uno:

if ($Param{Action} eq "Login") {
# get params
my $PostUser = $CommonObject{ParamObject}->GetParam(Param => 'User') || '';
my $PostPw = $CommonObject{ParamObject}->GetParam(Param => 'Password') || '';
# create AuthObject
my $AuthObject = Kernel::System::CustomerAuth->new(%CommonObject);
# check submited data
my $User = $AuthObject->Auth(User => $PostUser, Pw => $PostPw);
if ($User) {
# get user data
my %UserData = $CommonObject{UserObject}->CustomerUserDataGet(User => $User, Valid => 1);
# check needed data
if (!$UserData{UserID} || !$UserData{UserLogin}) {
if ($CommonObject{ConfigObject}->Get('CustomerPanelLoginURL')) {
# redirect to alternate login
print $CommonObject{LayoutObject}->Redirect(
ExtURL => $CommonObject{ConfigObject}->Get('CustomerPanelLoginURL')."?Reason=SystemError ",
);
}
else {
# show login screen
print $CommonObject{LayoutObject}->CustomerLogin(
Title => 'Panic!',
Message => 'Panic! No UserData!!!',
%Param,
);
exit (0);
}
}
# last login preferences update
$CommonObject{UserObject}->SetPreferences(
UserID => $UserData{UserID},
Key => 'UserLastLogin',
Value => $CommonObject{TimeObject}->SystemTime(),
);
# create new session id
my $NewSessionID = $CommonObject{SessionObject}->CreateSessionID(
%UserData,
UserLastRequest => $CommonObject{TimeObject}->SystemTime(),
UserType => 'Customer',
);
# create a new LayoutObject with SessionIDCookie
my $Expires = '+'.$CommonObject{ConfigObject}->Get('SessionMaxTime').'s';
if (!$CommonObject{ConfigObject}->Get('SessionUseCookieAfterBrowserClose')) {
$Expires = '';
}
my $LayoutObject = Kernel::Output::HTML::Generic->new(
SetCookies => {
SessionIDCookie => $CommonObject{ParamObject}->SetCookie(
Key => $Param{SessionName},
Value => $NewSessionID,
Expires => $Expires,
),
},
SessionID => $NewSessionID,
SessionName => $Param{SessionName},
%CommonObject,
);

# --
# redirect with new session id and old params
# --
# prepare old redirect URL -- do not redirect to Login or Logout (loop)!
if ($Param{RequestedURL} =~ /Action=(Logout|Login)/) {
$Param{RequestedURL} = '';
}
# redirect with new session id
print $LayoutObject->Redirect(OP => "$Param{RequestedURL}");
}
# --
# login is vailid
# --
else {
if ($CommonObject{ConfigObject}->Get('CustomerPanelLoginURL')) {
# redirect to alternate login
$Param{RequestedURL} = $CommonObject{LayoutObject}->LinkEncode($Param{RequestedURL});
print $CommonObject{LayoutObject}->Redirect(
ExtURL => $CommonObject{ConfigObject}->Get('CustomerPanelLoginURL').
"?Reason=LoginFailed&RequestedURL=$Param{Requested URL}",
);
}
else {
# show normal login
print $CommonObject{LayoutObject}->CustomerLogin(
Title => 'Login',
Message => $CommonObject{LogObject}->GetLogEntry(
Type => 'Info',
What => 'Message',
) || 'Login failed! Your username or password was entered incorrectly.',
User => $User,
%Param,
);
}
}

RootK 22/08/2005 09:04

Cita:

Iniciado por Nombela
y que esta hecho en PERL en la base de datos mete prjqSmRFQBP7c. Y no se como hace para sacar ese resultado.

Y no sería más fácil que tomes las clases de encriptación del framework..?? por lo que veo .. esa codificación es de un algoritmo con base64, hace tiempo puse un ejemplo para encriptar.. creo que sería más fácil que tratar de pasar código perl a .net...

Salu2

xknown 22/08/2005 16:32

Hmm, dudo mucho que pueda hacer algo más, primero porque no tengo ni idea de como esté estructurado esa aplicación en Perl (del cuál tengo un vago recuerdo de cuando era joven :-D), además con los archivos que mostraste, IMHO, no es suficiente para que alguien pueda ayudarte y la segunda razón es que no tengo demasiado tiempo...; creo que te toca aprender un poco de Perl

Cita:

Iniciado por RootK
Y no sería más fácil que tomes las clases de encriptación del framework..?? por lo que veo .. esa codificación es de un algoritmo con base64, hace tiempo puse un ejemplo para encriptar.. creo que sería más fácil que tratar de pasar código perl a .net...

Según dijo unos mensajes más arriba, es para mantener una compatibilidad con una aplicación en Perl que guarda los passwords en ese formato

Saludos

Nombela 23/08/2005 05:51

Gracias por la ayuda prestada pero despues de intentarlo de muchas formas, me he decidido a intentar inhabilitar el proceso de encryptacion en la aplicacion de perl para que asi la contraseña se escriba directamente en la base de datos.

hasta otra


La zona horaria es GMT -6. Ahora son las 11:50.

Desarrollado por vBulletin® Versión 3.8.7
Derechos de Autor ©2000 - 2026, Jelsoft Enterprises Ltd.