El pseudo-dispositivo /dev/urandom
, junto con dd
, puede hacer esto para usted:
dd if=/dev/urandom of=newfile bs=1M count=10
Esto creará un archivo de tamaño newfile
10M.
El dispositivo /dev/random
a menudo bloqueará si no hay suficiente aleatoriedad acumulada, urandom
no se bloqueará. Si está utilizando la aleatoriedad para material criptográfico, puede alejarse de urandom
. Para cualquier otra cosa, debería ser suficiente y muy probablemente más rápido.
Si quiere corromper solo algunos bits de su archivo (no el archivo completo), puede simplemente usar las funciones aleatorias de estilo C. Simplemente use rnd()
para calcular un desplazamiento y longitud n
, luego úselo n
veces para tomar bytes aleatorios para sobrescribir su archivo.
El siguiente script Perl muestra cómo se puede hacer esto (y sin tener que preocuparse de compilar código C):
use strict;
use warnings;
sub corrupt ($$$$) {
# Get parameters, names should be self-explanatory.
my $filespec = shift;
my $mincount = shift;
my $maxcount = shift;
my $charset = shift;
# Work out position and size of corruption.
my @fstat = stat ($filespec);
my $size = $fstat[7];
my $count = $mincount + int (rand ($maxcount + 1 - $mincount));
my $pos = 0;
if ($count >= $size) {
$count = $size;
} else {
$pos = int (rand ($size - $count));
}
# Output for debugging purposes.
my $last = $pos + $count - 1;
print "'$filespec', $size bytes, corrupting $pos through $last\n";
# Open file, seek to position, corrupt and close.
open (my $fh, "+<$filespec") || die "Can't open $filespec: $!";
seek ($fh, $pos, 0);
while ($count-- > 0) {
my $newval = substr ($charset, int (rand (length ($charset) + 1)), 1);
print $fh $newval;
}
close ($fh);
}
# Test harness.
system ("echo =========="); #DEBUG
system ("cp base-testfile testfile"); #DEBUG
system ("cat testfile"); #DEBUG
system ("echo =========="); #DEBUG
corrupt ("testfile", 8, 16, "ABCDEFGHIJKLMNOPQRSTUVWXYZ ");
system ("echo =========="); #DEBUG
system ("cat testfile"); #DEBUG
system ("echo =========="); #DEBUG
Consiste en la función corrupt
que llama con un nombre de archivo, tamaño mínimo y máximo de corrupción y un conjunto de caracteres para extraer la corrupción. El bit en la parte inferior es solo un código de prueba de unidad. A continuación se muestra un ejemplo de salida, donde se puede ver que una sección del archivo se ha corrompido:
==========
this is a file with nothing in it except for lowercase
letters (and spaces and punctuation and newlines).
that will make it easy to detect corruptions from the
test program since the character range there is from
uppercase a through z.
i have to make it big enough so that the random stuff
will work nicely, which is why i am waffling on a bit.
==========
'testfile', 344 bytes, corrupting 122 through 135
==========
this is a file with nothing in it except for lowercase
letters (and spaces and punctuation and newlines).
that will make iFHCGZF VJ GZDYct corruptions from the
test program since the character range there is from
uppercase a through z.
i have to make it big enough so that the random stuff
will work nicely, which is why i am waffling on a bit.
==========
Está probado en un nivel básico pero puede encontrar que hay casos de error de borde que necesitan ser atendidos. Haz con él lo que quieras.
+1 correcta - aunque es posible que desee para explicar la diferencia entre el azar y urandom ... – Konerak
en realidad tenía usar 10M para dd arg 'bs' – Benoit
'urandom' no es tan rápido como me gustaría. 'urandom' genera secuencias lo suficientemente buenas para crear claves privadas. No necesito esas garantías pero quiero más velocidad. – akostadinov