Foros del Web » Programación para mayores de 30 ;) » .NET »

Ayuda sobre codigo en Perl

Estas en el tema de Ayuda sobre codigo en Perl en el foro de .NET en Foros del Web. 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 ...
  #1 (permalink)  
Antiguo 27/07/2005, 04:32
Avatar de Nombela  
Fecha de Ingreso: abril-2005
Mensajes: 611
Antigüedad: 19 años
Puntos: 1
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.

Última edición por Nombela; 28/07/2005 a las 02:59
  #2 (permalink)  
Antiguo 27/07/2005, 04:41
 
Fecha de Ingreso: junio-2003
Ubicación: Asturias
Mensajes: 2.429
Antigüedad: 20 años, 10 meses
Puntos: 7
mmm, creo que .NET soporta perl, ¿No?
__________________
Charlie.
  #3 (permalink)  
Antiguo 27/07/2005, 05:45
Avatar de Nombela  
Fecha de Ingreso: abril-2005
Mensajes: 611
Antigüedad: 19 años
Puntos: 1
no lo se pero seria cojonudo la verdad
  #4 (permalink)  
Antiguo 27/07/2005, 09:47
 
Fecha de Ingreso: junio-2003
Ubicación: Asturias
Mensajes: 2.429
Antigüedad: 20 años, 10 meses
Puntos: 7
http://aspn.activestate.com/ASPN/NET

http://aspn.activestate.com/ASPN/Downloads/PerlASPX/
__________________
Charlie.
  #5 (permalink)  
Antiguo 28/07/2005, 01:02
Avatar de Nombela  
Fecha de Ingreso: abril-2005
Mensajes: 611
Antigüedad: 19 años
Puntos: 1
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
  #6 (permalink)  
Antiguo 29/07/2005, 09:38
Avatar de Nombela  
Fecha de Ingreso: abril-2005
Mensajes: 611
Antigüedad: 19 años
Puntos: 1
Nadie sabe un poquito de Perl que me pueda echar una mano???

gracias
  #7 (permalink)  
Antiguo 17/08/2005, 03:22
Avatar de Nombela  
Fecha de Ingreso: abril-2005
Mensajes: 611
Antigüedad: 19 años
Puntos: 1
Help Please!!!

Help Please!!!
  #8 (permalink)  
Antiguo 17/08/2005, 11:18
Avatar de xknown  
Fecha de Ingreso: diciembre-2004
Ubicación: Cusco - Perú
Mensajes: 2.248
Antigüedad: 19 años, 4 meses
Puntos: 7
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
__________________
Alex Concha
Buayacorp - Programación y Diseño
  #9 (permalink)  
Antiguo 18/08/2005, 01:41
Avatar de Nombela  
Fecha de Ingreso: abril-2005
Mensajes: 611
Antigüedad: 19 años
Puntos: 1
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.
  #10 (permalink)  
Antiguo 18/08/2005, 13:06
Avatar de xknown  
Fecha de Ingreso: diciembre-2004
Ubicación: Cusco - Perú
Mensajes: 2.248
Antigüedad: 19 años, 4 meses
Puntos: 7
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
__________________
Alex Concha
Buayacorp - Programación y Diseño
  #11 (permalink)  
Antiguo 19/08/2005, 01:50
Avatar de Nombela  
Fecha de Ingreso: abril-2005
Mensajes: 611
Antigüedad: 19 años
Puntos: 1
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
__________________
:si: El hombre es el único animal que come sin tener hambre, bebe sin tener sed y habla sin tener nada que decir. :si:

Última edición por Nombela; 19/08/2005 a las 02:05
  #12 (permalink)  
Antiguo 19/08/2005, 13:05
Avatar de xknown  
Fecha de Ingreso: diciembre-2004
Ubicación: Cusco - Perú
Mensajes: 2.248
Antigüedad: 19 años, 4 meses
Puntos: 7
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
__________________
Alex Concha
Buayacorp - Programación y Diseño
  #13 (permalink)  
Antiguo 22/08/2005, 02:07
Avatar de Nombela  
Fecha de Ingreso: abril-2005
Mensajes: 611
Antigüedad: 19 años
Puntos: 1
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;
__________________
:si: El hombre es el único animal que come sin tener hambre, bebe sin tener sed y habla sin tener nada que decir. :si:
  #14 (permalink)  
Antiguo 22/08/2005, 02:09
Avatar de Nombela  
Fecha de Ingreso: abril-2005
Mensajes: 611
Antigüedad: 19 años
Puntos: 1
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);
__________________
:si: El hombre es el único animal que come sin tener hambre, bebe sin tener sed y habla sin tener nada que decir. :si:
  #15 (permalink)  
Antiguo 22/08/2005, 02:18
Avatar de Nombela  
Fecha de Ingreso: abril-2005
Mensajes: 611
Antigüedad: 19 años
Puntos: 1
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,
);
}
}
__________________
:si: El hombre es el único animal que come sin tener hambre, bebe sin tener sed y habla sin tener nada que decir. :si:
  #16 (permalink)  
Antiguo 22/08/2005, 09:04
Avatar de RootK
Moderador
 
Fecha de Ingreso: febrero-2002
Ubicación: México D.F
Mensajes: 8.004
Antigüedad: 22 años, 2 meses
Puntos: 50
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
__________________
Nadie roba nada ya que en la vida todo se paga . . .

Exentrit - Soluciones SharePoint & Net
  #17 (permalink)  
Antiguo 22/08/2005, 16:32
Avatar de xknown  
Fecha de Ingreso: diciembre-2004
Ubicación: Cusco - Perú
Mensajes: 2.248
Antigüedad: 19 años, 4 meses
Puntos: 7
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 ), 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
__________________
Alex Concha
Buayacorp - Programación y Diseño
  #18 (permalink)  
Antiguo 23/08/2005, 05:51
Avatar de Nombela  
Fecha de Ingreso: abril-2005
Mensajes: 611
Antigüedad: 19 años
Puntos: 1
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
__________________
:si: El hombre es el único animal que come sin tener hambre, bebe sin tener sed y habla sin tener nada que decir. :si:
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 06:54.