Proyectos de Subversion Android Microlearning

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
package com.cesams.twogetskills.library;
2
import java.util.*;
3
 
4
public abstract class RSA {
5
	private static long  mo(long g, long l)
6
	{
7
		long result = g - (l * (long) Math.floor(g/l));
8
		return result;
9
	}
10
 
11
	private static long powmod(long base, long exp, long modulus) {
12
		 long accum = 1;
13
		 int i = 0;
14
		 long basepow2 = base;
15
		 while ((exp >> i)>0)
16
		 {
17
			 if (((exp >> i) & 1) == 1)
18
			 {
19
				 accum = mo((accum * basepow2) , modulus);
20
			 }
21
			 basepow2 = mo((basepow2 * basepow2) , modulus);
22
			 i++;
23
		 }
24
		 return accum;
25
	}
26
 
27
	public static String decode(String c, long d,  long n)
28
	{
29
		 String[] decryptarray = c.split(" ");
30
 
31
		 //Each number is then decrypted using the RSA formula: block ^D mod N
32
		 StringBuffer deencrypt = new StringBuffer();
33
		 for (int u=0; u < decryptarray.length; u++)
34
		 	{
35
			 	if(decryptarray[u].equals("")) {
36
			 		continue;
37
			 	}
38
			 	String resultmod = String.valueOf(powmod(Long.valueOf(decryptarray[u]), d, n));
39
			 	deencrypt.append(resultmod.substring(1, resultmod.length() - 1));
40
		 }
41
		 String s = deencrypt.toString();
42
 
43
		 StringBuffer resultd = new StringBuffer();
44
		 for (int u=0;  u< s.length() ; u+=2)
45
		 {
46
			 String num = s.substring(u, u + 2);
47
			 int i = Integer.valueOf(num) + 30;
48
		     char ch  = (char) i;
49
 
50
			 resultd.append(ch);
51
 
52
		 }
53
		 return resultd.toString();
54
	}
55
 
56
  public static String encode (String m, long e, long n) {
57
  	Vector<String> array = new Vector<String>();
58
 
59
  	 for (int i=0;  i<m.length(); i+=3) {
60
  	   String tmpasci="1";
61
  	   for (int h=0;  h<3; h++) {
62
  		   String tmpstr = "";
63
  		   if (i+ h < m.length()) {
64
  			   int aux = m.charAt(i + h);
65
  			   tmpstr =  String.valueOf(aux - 30);
66
  			   if (tmpstr.length() < 2) {
67
  				   tmpstr = '0' + tmpstr;
68
  			   }
69
  		   } else {
70
  			   break;
71
  		   }
72
  		   tmpasci = tmpasci + tmpstr;
73
  	  }
74
  	   tmpasci = tmpasci +  '1';
75
  	  array.add(tmpasci);
76
  	 }
77
  	 StringBuffer coded = new StringBuffer();
78
  	 for (int k=0; k<array.size(); k++) {
79
  		 long resultmod = powmod(Long.valueOf(array.elementAt(k)), e, n);
80
  		 coded.append( String.valueOf(resultmod));
81
  		 coded.append(" ");
82
  	 }
83
  	 return coded.toString();
84
 	}
85
}