Generate random valid norwegian SSN


/ Published in: Perl
Save to your folder(s)

Generates a random valid norwegian SSN for dates between 1900 and 1999


Copy this code and paste it in your HTML
  1. #
  2. # random_norwegian_ssn()
  3. #
  4. # Accepts one parameter, a date string in the format DDMMYY.
  5. #
  6. sub random_norwegian_ssn {
  7. my $date = shift;
  8.  
  9. # Extract date, month, year
  10. my $d1 = substr($date,0,1);
  11. my $d2 = substr($date,1,1);
  12. my $m1 = substr($date,2,1);
  13. my $m2 = substr($date,3,1);
  14. my $y1 = substr($date,4,1);
  15. my $y2 = substr($date,5,1);
  16.  
  17. my ($i1, $i2, $i3);
  18. my ($c1, $c2);
  19.  
  20. do {
  21. # SSNs for dates between 1900-1999 use an entity number between 0-499
  22. my $random_num = int(rand(499));
  23.  
  24. # Pad the entity number to 3 numbers
  25. my $padded_num = sprintf("%03d", $random_num);
  26. ($i1, $i2, $i3) = split(//, $padded_num);
  27.  
  28. # Calculate the two control numbers
  29. my $v1 = (3*$d1) + (7*$d2) + (6*$m1) + $m2 + (8*$y1) + (9*$y2) + (4*$i1) + (5*$i2) + (2*$i3);
  30. $c1 = ($v1 % 11) == 0 ? 0 : 11-($v1 % 11);
  31.  
  32. my $v2 = (5*$d1) + (4*$d2) + (3*$m1) + (2*$m2) + (7*$y1) + (6*$y2) + (5*$i1) +(4*$i2) + (3*$i3) + (2*$c1);
  33. $c2 = ($v2 % 11) == 0 ? 0 : 11-($v2 % 11);
  34.  
  35. } until ($c1 < 10 && $c2 < 10);
  36.  
  37. return "$d1$d2$m1$m2$y1$y2$i1$i2$i3$c1$c2";
  38. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.