AES,RSA,ECC加密算法实现

来源:互联网 发布:戴立忍事件知乎 编辑:程序博客网 时间:2024/06/04 18:07

 

RSA算法:

[java] view plaincopy
  1. package key;  
  2. import java.math.BigInteger;  
  3. import java.util.Random;  
  4.   
  5.   
  6. public class RSA extends Cryption{  
  7.      KEY ku;//公钥  
  8.      KEY kr;//私钥  
  9.       
  10.      public RSA() {  
  11.         Random r = new Random();  
  12.         BigInteger p,q,n,nn;  
  13.   
  14.         BigInteger e = BigInteger.ONE;// = new BigInteger(3+"");  
  15.         BigInteger d = BigInteger.ONE;  
  16.         //素数p,q,e,d  
  17.         while(true) {  
  18.             p = BigInteger.probablePrime(17, r);//new BigInteger(7+"");  
  19.             q = BigInteger.probablePrime(19, r);//new BigInteger(5+"");  
  20.               
  21.             n = p.multiply(q);  
  22.               
  23.             nn = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));  
  24.             if(nn.longValue() > 65535) {  
  25.   
  26.                 for(int i=3; i<nn.intValue(); i++) {  
  27.                     if(MyMath.gcd(i, nn.intValue()) == 1) {  
  28.                         e = BigInteger.valueOf(i);  
  29.                           
  30.                         if(MyMath.exgcd(e, nn).longValue() == -1)  
  31.                             continue;  
  32.                         else  
  33.                             break;  
  34.                     }  
  35.                 }  
  36.                 d = MyMath.exgcd(e, nn).mod(nn);  
  37.                 BigInteger big = d.multiply(d);big = big.multiply(big);  
  38.                 if(big.compareTo(n) > 0) {  
  39.                     break;  
  40.                 }  
  41.                 else  
  42.                     continue;  
  43.             }  
  44.               
  45.         }  
  46.           
  47.         this.ku = new KEY(e,n);  
  48.         this.kr = new KEY(d,n);  
  49.      }  
  50.       
  51.     public RSA(KEY ku, KEY kr) {  
  52.         super();  
  53.         this.ku = ku;  
  54.         this.kr = kr;  
  55.     }  
  56.     class KEY {  
  57.         BigInteger x;  
  58.         BigInteger n;  
  59.         public KEY(BigInteger x, BigInteger n) {  
  60.             super();  
  61.             this.x = x;  
  62.             this.n = n;  
  63.         }  
  64.           
  65.     }  
  66.     //加密  
  67.     public String Encryption(String s, KEY key) {  
  68.         StringBuffer sb = new StringBuffer();  
  69.         char[] cs = s.toCharArray();  
  70.         for(int i=0; i<cs.length; i++) {  
  71.             int k = cs[i];  
  72.             if(k < key.n.longValue())  
  73.             {  
  74.                 BigInteger p = new BigInteger(k+"");  
  75.                 int kk = Integer.parseInt(MyMath.reaminder(key.n, p,Long.parseLong(key.x.toString())).toString());  
  76.                 char c =(char)kk;  
  77.                 sb.append(c);  
  78.             }  
  79.             else {  
  80.                 sb.append(cs[i]);  
  81.             }  
  82.         }  
  83.         return sb.toString();  
  84.     }  
  85.     //加密成16进制字符串  
  86.     public String Encryption(String s) {  
  87.         StringBuffer sb = new StringBuffer();  
  88.         char[] cs = s.toCharArray();  
  89.         for(int i=0; i<cs.length; i++) {  
  90.             int k = cs[i];  
  91.             if(k < this.ku.n.longValue())  
  92.             {  
  93.                 BigInteger p = new BigInteger(k+"");  
  94.                 long kk = Long.parseLong(MyMath.reaminder(this.ku.n, p,Long.parseLong(this.ku.x.toString())).toString());  
  95.                 sb.append(Long.toHexString(kk));  
  96.                 sb.append(" ");  
  97.             }  
  98.             else {  
  99.                 sb.append(Integer.toHexString(k));  
  100.                 sb.append(" ");  
  101.             }  
  102.         }  
  103.         return sb.toString();  
  104.     }  
  105.     //解密  
  106.     public String Decryption(String s, KEY key) {  
  107.         return Encryption(s,key);  
  108.     }  
  109.     public String Decryption(String s) {  
  110.         StringBuffer sb = new StringBuffer();  
  111.         String[] ss = s.split(" ");  
  112.         for(int i=0; i<ss.length; i++) {  
  113.             long k = Long.parseLong(ss[i], 16);  
  114.             BigInteger p = new BigInteger(k+"");  
  115.             int kk = Integer.parseInt(MyMath.reaminder(this.kr.n, p,Long.parseLong(this.kr.x.toString())).toString());  
  116.             sb.append(Tools.obox(Integer.toHexString(kk), 4));  
  117.         }  
  118.         return Tools.hexStr2Str(sb.toString());  
  119.     }  
  120.       
  121.     public static void main(String[] args) {  
  122.         RSA rsa = new RSA();  
  123.         String s = "大家好abi 是低估 斯蒂芬和欧冠发 蛋糕房女生佛 ,;";  
  124.         String sa = rsa.Encryption(s);  
  125.         System.out.println("密文:    " + sa);  
  126.         System.out.println("明文:    " + rsa.Decryption(sa));  
  127.         System.out.println("e:"+rsa.kr.x + "  d:" + rsa.ku.x +"   n:" + rsa.kr.n);  
  128.     }  
  129. }  

 

ECC算法

[java] view plaincopy
  1. package key;  
  2. import java.math.BigInteger;  
  3. import java.util.Random;  
  4.   
  5. public class ECC extends Cryption{  
  6.     static E e;//椭圆曲线  
  7.     Pare pare;//椭圆上的已知点  
  8.     long privatekey;//7位速度变慢            私钥--随机  
  9.     Pare publickey;//公钥  
  10.       
  11.     public ECC() {  
  12.         super();  
  13.         Random rand = new Random();  
  14.         this.e = new E(BigInteger.probablePrime(30, rand).intValue(),rand.nextInt(1024),rand.nextInt(1024));  
  15.         this.privatekey = rand.nextInt(1024);//7位速度变慢            私钥--随机  
  16.         this.pare = new Pare(rand.nextInt(10000000),rand.nextInt(10000000));  
  17.         this.publickey = this.pare.multiply(privatekey);//new Pare();  
  18.     }  
  19.     class E {// 表示椭圆曲线方程  
  20.         Long p;//模p的椭圆群  
  21.         Long a;  
  22.         Long b;  
  23.         public E(long p, long a, long b) {  
  24.             super();  
  25.             this.p = p;  
  26.             this.a = a;  
  27.             this.b = b;  
  28.         }  
  29.           
  30.     }  
  31.     class Message {//传送消息的最小单元  
  32.         Pare pa;  
  33.         Pare pb;  
  34.         public Message(Pare pa, Pare pb) {  
  35.             super();  
  36.             this.pa = pa;  
  37.             this.pb = pb;  
  38.         }  
  39.         public String toString() {  
  40.             return this.pa.toString() +" "this.pb.toString();  
  41.         }  
  42.     }  
  43.     class Pare {//椭圆曲线上的点(x,y)  
  44.         long x;  
  45.         long y;  
  46.         public Pare() {  
  47.             super();  
  48.         }  
  49.         public Pare(long x, long y) {  
  50.             super();  
  51.   
  52.             this.x = x;  
  53.             this.y = y;  
  54.         }  
  55.         //加法  
  56.         public Pare add(Pare pare) {  
  57.             if(this.x == Integer.MAX_VALUE) {//为无穷大时O+P=P  
  58.                 return pare;  
  59.             }  
  60.             Pare res = new Pare();  
  61.             if(this.y==pare.y && this.x==pare.x) {//相等时  
  62.                 long d = moddivision(3*this.x*this.x + ECC.e.a,ECC.e.p,2*this.y);  
  63.                   
  64.                 res.x = d*d - 2*this.x;  
  65.                 res.x = mod(res.x, ECC.e.p);  
  66.                   
  67.                 res.y = d*(this.x - res.x) - this.y;  
  68.                 res.y = mod(res.y, ECC.e.p);  
  69.             }  
  70.             else if(pare.x - this.x != 0) {  
  71.                 long d = moddivision(pare.y - this.y,ECC.e.p,pare.x - this.x);  
  72.                 res.x = d*d - this.x - pare.x;  
  73.                 res.x = mod(res.x, ECC.e.p);  
  74.                   
  75.                 res.y = d*(this.x - res.x) - this.y;  
  76.                 res.y = mod(res.y, ECC.e.p);  
  77.             }  
  78.             else {//P Q互逆,返回无穷大  
  79.                 res.x = Integer.MAX_VALUE;  
  80.                 res.y = Integer.MAX_VALUE;  
  81.             }  
  82.               
  83.             return res;  
  84.         }  
  85.         //减法  
  86.         public Pare less(Pare p) {  
  87.             p.y *= -1;  
  88.             return add(p);  
  89.         }  
  90.         //乘法  
  91.         public Pare multiply(long num) {  
  92.             Pare p = new Pare(this.x,this.y);  
  93.             for(long i=1; i<num; i++) {  
  94.                 p = p.add(this);  
  95.             }  
  96.             return p;  
  97.         }  
  98.         //求余,解决负号问题  
  99.         public long mod(long a, long b) {  
  100.             a = a%b;  
  101.             while(a<0) {  
  102.                 a += b;  
  103.             }  
  104.             return a;  
  105.         }  
  106.         //求余取商(a mod b)/c  
  107.         /*public long moddivision(long a, long b, long c) { 
  108.             a = mod(a,b); 
  109.             while(a%c != 0) { 
  110.                 a += b; 
  111.             } 
  112.             a = a/c; 
  113.             return a; 
  114.         }*/  
  115.         public long moddivision(long a, long b, long c) {  
  116.             a = mod(a,b);  
  117.             c = mod(c,b);  
  118.             a = a*MyMath.exgcd(c,b);  
  119.             return mod(a,b);  
  120.         }  
  121.         public String toString() {  
  122.             return Tools.obox(Tools.long2hexStr(this.x), 4) + " " + Tools.obox(Tools.long2hexStr(this.y), 4);  
  123.         }  
  124.     }  
  125.       
  126.     //加密  
  127.     public Message encryption(Pare g,Pare pbk,Pare word) {  
  128.         pbk = g.multiply(privatekey);//公钥  
  129.         int d = new Random().nextInt(1024);//随机数  
  130.         Pare dg = g.multiply(d);  
  131.         Pare dp = pbk.multiply(d);  
  132.         Pare send = word.add(dp);  
  133.         return new Message(dg,send);  
  134.     }  
  135.     public String encryption(Pare g, Pare pbk, String word) {  
  136.         StringBuffer sb = new StringBuffer();  
  137.         Pare[] words = Str2Pares(word);  
  138.         for(int i=0; i<words.length; i++) {  
  139.             sb.append(encryption(g,pbk,words[i]).toString());  
  140.             sb.append(" ");  
  141.         }  
  142.         return sb.toString();  
  143.     }  
  144.     public String encryption(String word) {  
  145.         StringBuffer sb = new StringBuffer();  
  146.         Pare[] words = Str2Pares(word);  
  147.         for(int i=0; i<words.length; i++) {  
  148.             sb.append(encryption(this.pare,this.publickey,words[i]).toString());  
  149.             sb.append(" ");  
  150.         }  
  151.         return sb.toString();  
  152.     }  
  153.       
  154.     //解密  
  155.     public Pare decryption(Message m) {  
  156.         Pare pab = m.pa.multiply(this.privatekey);  
  157.         Pare result = m.pb.less(pab);  
  158.         return result;  
  159.     }  
  160.     public String decryption(String s) {  
  161.         StringBuffer sb = new StringBuffer();  
  162.         Message[] mes = hexStr2Messages(s);  
  163.         for(int i=0; i<mes.length; i++) {  
  164.             sb.append(decryption(mes[i]).toString());  
  165.         }  
  166.         return Tools.hexStr2Str(sb.toString().replace(" """));  
  167.     }  
  168.       
  169.     public static void print(Object o) {  
  170.         System.out.println(o);  
  171.     }  
  172.     //将字符串转换为   值对  
  173.     public Pare[] Str2Pares(String string) {  
  174.           
  175.         Pare[] pares ;  
  176.         if(string.length()%2 != 0)   
  177.             pares = new Pare[string.length()/2+1];  
  178.         else  
  179.             pares = new Pare[string.length()/2];  
  180.         char[] chars = string.toCharArray();  
  181.         int i=0;  
  182.         for(i=0; i<string.length()/2; i++) {  
  183.             pares[i] = new Pare(chars[i*2],chars[i*2+1]);  
  184.         }  
  185.         if(string.length()%2 != 0)   
  186.             pares[i] = new Pare(chars[i*2],0);  
  187.         return pares;  
  188.     }  
  189.     //将值对转换成16进制字符串  
  190.     public String Pares2hexStr(Pare[] pares) {        
  191.         StringBuffer s = new StringBuffer();  
  192.         for(int i=0; i<pares.length; i++) {  
  193.             s.append(pares[i].toString());  
  194.         }  
  195.         return s.toString();  
  196.     }  
  197.     //将16进制字符串转为     消息串  
  198.     public Message[] hexStr2Messages(String s) {  
  199.         String[] ss = s.split(" ");  
  200.         Message[] mes = new Message[ss.length/4];  
  201.         for(int i=0; i<mes.length; i++) {  
  202.             long pax = Tools.hexStr2long(ss[i*4]);  
  203.             long pay = Tools.hexStr2long(ss[i*4+1]);  
  204.             long pbx = Tools.hexStr2long(ss[i*4+2]);  
  205.             long pby = Tools.hexStr2long(ss[i*4+3]);  
  206.             mes[i] = new Message(new Pare(pax,pay),new Pare(pbx,pby));  
  207.         }  
  208.         return mes;  
  209.     }  
  210.     //将消息串转为16进制字符串  
  211.     public String Messages2hexStr(Message[] mes) {  
  212.         StringBuffer sb = new StringBuffer();  
  213.         for(int i=0; i<mes.length; i++) {  
  214.             sb.append(mes[i].toString());  
  215.             sb.append(" ");  
  216.         }  
  217.         return sb.toString();  
  218.     }  
  219.     public static void main(String[] args) {  
  220.         ECC ecc = new ECC();  
  221.         print("私钥:" + ecc.privatekey);  
  222.         print("公钥:" + ecc.publickey);  
  223.         print("基点:" + ecc.pare);  
  224.         print("");  
  225.         String s = "大家好啊abc123aaaaa sadfasdfe asf";  
  226.           
  227.         String jm = ecc.encryption(s);  
  228.         //System.out.print("密文:  " +jm);  
  229.         print("密文:   " + jm);  
  230.         String mw = ecc.decryption(jm);  
  231.         System.out.print("明文:  ");  
  232.         print("明文:   " +mw);  
  233.           
  234.     }  
  235. }  

 

 

AES算法:

[java] view plaincopy
  1. package key;  
  2. import java.util.Random;  
  3.   
  4. public class AES extends Cryption{  
  5.     String key;//密钥  
  6.     int round;//加密轮数  
  7.       
  8.     public AES() {  
  9.         super();  
  10.         this.key = key();  
  11.         this.round = new Random().nextInt(100);  
  12.     }  
  13.       
  14.     public AES(String key, int round) {  
  15.         super();  
  16.         this.key = key;  
  17.         this.round = round;  
  18.     }  
  19.   
  20.     //S盒  
  21.     static final String[][] Sbox = {  
  22.         {"63","7c","77","7b","f2","6b","6f","c5","30","01","67","2b","fe","d7","ab","76"},  
  23.         {"ca","82","c9","7d","fa","59","47","f0","ad","d4","a2","af","9c","a4","72","c0"},  
  24.         {"b7","fd","93","26","36","3f","f7","cc","34","a5","e5","f1","71","d8","31","15"},  
  25.         {"04","c7","23","c3","18","96","05","9a","07","12","80","e2","eb","27","b2","75"},  
  26.         {"09","83","2c","1a","1b","6e","5a","a0","52","3b","d6","b3","29","e3","2f","84"},  
  27.         {"53","d1","00","ed","20","fc","b1","5b","6a","cb","be","39","4a","4c","58","cf"},  
  28.         {"d0","ef","aa","fb","43","4d","33","85","45","f9","02","7f","50","3c","9f","a8"},  
  29.         {"51","a3","40","8f","92","9d","38","f5","bc","b6","da","21","10","ff","f3","d2"},  
  30.         {"cd","0c","13","ec","5f","97","44","17","c4","a7","7e","3d","64","5d","19","73"},  
  31.         {"60","81","4f","dc","22","2a","90","88","46","ee","b8","14","de","5e","0b","db"},  
  32.         {"e0","32","3a","0a","49","06","24","5c","c2","d3","ac","62","91","95","e4","79"},  
  33.         {"e7","c8","37","6d","8d","d5","4e","a9","6c","56","f4","ea","65","7a","ae","08"},  
  34.         {"ba","78","25","2e","1c","a6","b4","c6","e8","dd","74","1f","4b","bd","8b","8a"},  
  35.         {"70","3e","b5","66","48","03","f6","0e","61","35","57","b9","86","c1","1d","9e"},  
  36.         {"e1","f8","98","11","69","d9","8e","94","9b","1e","87","e9","ce","55","28","df"},  
  37.         {"8c","a1","89","0d","bf","e6","42","68","41","99","2d","0f","b0","54","bb","16"}  
  38.     };  
  39.     //逆S盒  
  40.     static final String[][] InvSbox = {  
  41.         {"52","09","6a","d5","30","36","a5","38","bf","40","a3","9e","81","f3","d7","fb"},  
  42.         {"7c","e3","39","82","9b","2f","ff","87","34","8e","43","44","c4","de","e9","cb"},  
  43.         {"54","7b","94","32","a6","c2","23","3d","ee","4c","95","0b","42","fa","c3","4e"},  
  44.         {"08","2e","a1","66","28","d9","24","b2","76","5b","a2","49","6d","8b","d1","25"},  
  45.         {"72","f8","f6","64","86","68","98","16","d4","a4","5c","cc","5d","65","b6","92"},  
  46.         {"6c","70","48","50","fd","ed","b9","da","5e","15","46","57","a7","8d","9d","84"},  
  47.         {"90","d8","ab","00","8c","bc","d3","0a","f7","e4","58","05","b8","b3","45","06"},  
  48.         {"d0","2c","1e","8f","ca","3f","0f","02","c1","af","bd","03","01","13","8a","6b"},  
  49.         {"3a","91","11","41","4f","67","dc","ea","97","f2","cf","ce","f0","b4","e6","73"},  
  50.         {"96","ac","74","22","e7","ad","35","85","e2","f9","37","e8","1c","75","df","6e"},  
  51.         {"47","f1","1a","71","1d","29","c5","89","6f","b7","62","0e","aa","18","be","1b"},  
  52.         {"fc","56","3e","4b","c6","d2","79","20","9a","db","c0","fe","78","cd","5a","f4"},  
  53.         {"1f","dd","a8","33","88","07","c7","31","b1","12","10","59","27","80","ec","5f"},  
  54.         {"60","51","7f","a9","19","b5","4a","0d","2d","e5","7a","9f","93","c9","9c","ef"},  
  55.         {"a0","e0","3b","4d","ae","2a","f5","b0","c8","eb","bb","3c","83","53","99","61"},  
  56.         {"17","2b","04","7e","ba","77","d6","26","e1","69","14","63","55","21","0c","7d"}  
  57.           
  58.     };  
  59.     //字节代替  
  60.     public char[] subBytes(char[] state) {  
  61.         char[] result = new char[state.length];  
  62.         for(int i=0; i<state.length; i++) {  
  63.             String s = Integer.toHexString(state[i]);  
  64.             if(s.length() < 2) {  
  65.                 s = "0" + s;  
  66.             }  
  67.             String rs = Sbox[s.charAt(0) < 97 ?s.charAt(0)-48 : s.charAt(0)-87][s.charAt(1) < 97 ?s.charAt(1)-48 : s.charAt(1)-87];  
  68.             result[i] = (char) Integer.parseInt(rs, 16);  
  69.         }  
  70.         return result;  
  71.     }  
  72.     //逆字节代替  
  73.     public char[] invSubBytes(char[] state) {  
  74.         char[] result = new char[16];  
  75.         for(int i=0; i<state.length; i++) {  
  76.             String s = Integer.toHexString(state[i]);  
  77.             if(s.length() < 2) {  
  78.                 s = "0" + s;  
  79.             }  
  80.             String rs = InvSbox[s.charAt(0) < 97 ?s.charAt(0)-48 : s.charAt(0)-87][s.charAt(1) < 97 ?s.charAt(1)-48 : s.charAt(1)-87];  
  81.             result[i] = (char) Integer.parseInt(rs, 16);  
  82.         }  
  83.         return result;  
  84.     }  
  85.     //列混淆  
  86.     public char[] mixColumns(char[] state) {  
  87.         char[] lisa = {2,3,1,1};  
  88.         char[] result = new char[16];  
  89.         for(int col=0; col<4; col++) {  
  90.             char[] lisb = new char[4];  
  91.             int flagc = col;  
  92.             for(int m=0; m<4; m++){  
  93.                 lisb[m] = state[flagc];  
  94.                 flagc += 4;  
  95.             }  
  96.             for(int row=0; row<4; row++) {  
  97.                 int k = ffmul(lisb[0],lisa[(4-row)%4])^ffmul(lisb[1],lisa[(5-row)%4])^ffmul(lisb[2],lisa[(6-row)%4])^ffmul(lisb[3],lisa[(7-row)%4]);  
  98.                 result[row*4+col] = (char)k;  
  99.             }  
  100.         }  
  101.         return result;  
  102.     }  
  103.     //逆列混淆  
  104.     public char[] invMixColumns(char[] state) {  
  105.         char[] lisa = {14,11,13,9};  
  106.         char[] result = new char[16];  
  107.         for(int col=0; col<4; col++) {  
  108.             char[] lisb = new char[4];  
  109.             int flagc = col;  
  110.             for(int m=0; m<4; m++){  
  111.                 lisb[m] = state[flagc];  
  112.                 flagc += 4;  
  113.             }  
  114.             for(int row=0; row<4; row++) {  
  115.                 int k = ffmul(lisb[0],lisa[(4-row)%4])^ffmul(lisb[1],lisa[(5-row)%4])^ffmul(lisb[2],lisa[(6-row)%4])^ffmul(lisb[3],lisa[(7-row)%4]);  
  116.                 result[row*4+col] = (char)k;  
  117.             }  
  118.         }  
  119.         return result;  
  120.     }  
  121.     //字节乘法  
  122.     public int ffmul(int a, int b) {  
  123.         String ba = Integer.toBinaryString(a);  
  124.         int[] stor = new int[8];  
  125.         while(ba.length()<8) {  
  126.             ba = "0" + ba;  
  127.         }  
  128.         stor[0] = b;  
  129.         for(int i=1; i<8; i++) {  
  130.             String bb = Integer.toBinaryString(stor[i-1]);  
  131.             if(bb.length() < 8) {  
  132.                 stor[i] = leftshift(stor[i-1],1);  
  133.             }  
  134.             else  
  135.                 stor[i] = leftshift(stor[i-1],1) ^ 27;  
  136.         }  
  137.         int result = 0;  
  138.         for(int i=7; i>=0; i--) {  
  139.             if(ba.charAt(i) == '1') {  
  140.                 if(result == 0) {  
  141.                     result = stor[7-i];  
  142.                 }  
  143.                 else  
  144.                     result = result ^stor[7-i];   
  145.             }  
  146.         }  
  147.         return result;  
  148.     }  
  149.     //二进制数左移  
  150.     public int leftshift(int num, int step) {  
  151.         String ba = Integer.toBinaryString(num);  
  152.         while(ba.length()<8) {  
  153.             ba = "0" + ba;  
  154.         }  
  155.         for(int i=0; i<step; i++) {  
  156.             ba += "0";  
  157.         }  
  158.         return Integer.parseInt(ba.substring(step), 2);  
  159.     }  
  160.     //行移位  
  161.     public char[] shiftRows(char[] state) {  
  162.         char[][] in = new char[4][4];  
  163.         for(int i=0; i<4; i++) {  
  164.             for(int j=0; j<4; j++) {  
  165.                 in[i][j] = state[i*4+j];  
  166.             }  
  167.         }  
  168.         char[] result = new char[16];  
  169.         for(int i=0; i<4; i++) {  
  170.             for(int j=0; j<4; j++) {  
  171.                 result[i*4+j] = in[i][(j+i)%4];  
  172.             }  
  173.         }  
  174.         return result;  
  175.     }  
  176.     //逆行移位  
  177.     public char[] invShiftRows(char[] state) {  
  178.         char[][] in = new char[4][4];  
  179.         for(int i=0; i<4; i++) {  
  180.             for(int j=0; j<4; j++) {  
  181.                 in[i][j] = state[i*4+j];  
  182.             }  
  183.         }  
  184.         char[] result = new char[16];  
  185.         for(int i=0; i<4; i++) {  
  186.             for(int j=0; j<4; j++) {  
  187.                 int col = (j-i)>0?(j-i):(j-i)+4;  
  188.                 result[i*4+j] = in[i][col%4];  
  189.             }  
  190.         }  
  191.         return result;  
  192.     }  
  193.     //轮密钥加  
  194.     public char[] addRoundKey(char[] state, char[] key) {  
  195.         char[] result = new char[16];  
  196.         for(int col=0; col<4; col++) {  
  197.             for(int row=0; row<4; row++) {  
  198.                 result[row*4+col] =(char) (state[row*4+col] ^ key[row*4+col]);  
  199.             }  
  200.         }  
  201.         return result;  
  202.     }  
  203.   
  204.     //密钥扩展  
  205.     public char[][] keyExpansion(char[] key,int round) {  
  206.         char[] RC = new char[round];  
  207.         for(int i=0; i<round; i++) {  
  208.             if(i==0) {  
  209.                 RC[i] = 1;  
  210.             }  
  211.             else {  
  212.                 RC[i] =(char) ffmul(2, RC[i-1]);  
  213.             }  
  214.         }  
  215.           
  216.         char[][] newkey = new char[round][16];  
  217.         char[] start = {key[12],key[13],key[14],key[15]};  
  218.         for(int r=0; r<round; r++) {  
  219.             for(int i=3; i<7; i++) {  
  220.                 if(i==3) {  
  221.                     char ot = start[0];  
  222.                     start[0] = start[1];start[1] = start[2];  
  223.                     start[2] = start[3];start[3] = ot;//RotWord()  
  224.                     start = subBytes(start);  
  225.                     start = XOR(start,new char[]{RC[r],0,0,0});  
  226.                 }  
  227.                 char[] last = {key[(i-3)*4],key[(i-3)*4+1],key[(i-3)*4+2],key[(i-3)*4+3]};  
  228.                 start = XOR(start,last);  
  229.                 for(int k=0; k<4; k++) {  
  230.                     key[(i-3)*4 + k] = start[k];  
  231.                 }  
  232.                 for(int j=0; j<4; j++) {  
  233.                     newkey[r][(i+1)%4 + j*4] = start[j];  
  234.                 }  
  235.             }  
  236.         }  
  237.         return newkey;  
  238.     }  
  239.     //异或  
  240.     public char[] XOR(char[] a, char[] b) {  
  241.         char[] result = new char[a.length];  
  242.         for(int i=0; i<a.length; i++) {  
  243.             result[i] = (char)(((int)a[i])^((int) b[i]));  
  244.         }  
  245.         return result;  
  246.     }  
  247.     //字节加密  
  248.     public char[] cipher(char[] in,char[] key,int round) {  
  249.         char[] out = new char[16];  
  250.         char[] newword = new char[16];  
  251.         for(int i=0; i<16; i++) {  
  252.             newword[i] = key[i];  
  253.         }  
  254.         char[][] keys = keyExpansion(newword, round);   
  255.         in = exchange(in);key = exchange(key);  
  256.         in = addRoundKey(in, key);  
  257.           
  258.         for(int i=0; i<round-1; i++) {  
  259.             out = subBytes(in);  
  260.             out = shiftRows(out);  
  261.             out = mixColumns(out);  
  262.             in = addRoundKey(out, keys[i]);  
  263.         }  
  264.         out = subBytes(in);  
  265.         out = shiftRows(out);  
  266.         out = addRoundKey(out, keys[round-1]);  
  267.         return exchange(out);  
  268.     }  
  269.     //字符串加密  
  270.     public String cipher(String in,String key,int round) {  
  271.         StringBuffer sb = new StringBuffer();  
  272.         char[] keys = Tools.hexStr2Cs(key);  
  273.         String hexStr = Tools.Str2hexStr(in);  
  274.         while(hexStr.length()>=32) {  
  275.             String sin = hexStr.substring(032);  
  276.             hexStr = hexStr.substring(32);  
  277.             sb.append(Tools.Cs2hexStr(cipher(Tools.hexStr2Cs(sin),keys,round)));  
  278.         }  
  279.         if(hexStr.length()>0) {  
  280.             while(hexStr.length()<32) {  
  281.                 hexStr += "0";  
  282.             }  
  283.             sb.append(Tools.Cs2hexStr(cipher(Tools.hexStr2Cs(hexStr),keys,round)));  
  284.         }  
  285.         return sb.toString();  
  286.     }  
  287.     public String cipher(String in) {  
  288.         return cipher(in,this.key,this.round);  
  289.     }  
  290.     //字节解密  
  291.     public char[] inCipher(char[] in, char[] key, int round) {  
  292.         char[] out = new char[16];  
  293.         char[] newword = new char[16];  
  294.         for(int i=0; i<16; i++) {  
  295.             newword[i] = key[i];  
  296.         }  
  297.         char[][] keys = keyExpansion(newword, round);   
  298.         in = exchange(in);key = exchange(key);  
  299.         in = addRoundKey(in, keys[round-1] );  
  300.           
  301.         for(int i=0; i<round-1; i++) {  
  302.             out = invShiftRows(in);  
  303.             out = invSubBytes(out);  
  304.             out = addRoundKey(out, keys[round-2-i]);  
  305.             in = invMixColumns(out);  
  306.               
  307.         }  
  308.         out = invShiftRows(in);  
  309.         out = invSubBytes(out);  
  310.         out = addRoundKey(out,key);  
  311.         return exchange(out);  
  312.     }  
  313.     //字符串解密  
  314.     public String inCipher(String in, String key, int round) {  
  315.         StringBuffer sb = new StringBuffer();  
  316.         char[] keys = Tools.hexStr2Cs(key);  
  317.         String hexStr = in;//Str2hexStr(in);  
  318.         while(hexStr.length()>=32) {  
  319.             String sin = hexStr.substring(032);  
  320.             hexStr = hexStr.substring(32);  
  321.             sb.append(Tools.hexStr2Str(Tools.Cs2hexStr(inCipher(Tools.hexStr2Cs(sin),keys,round))));  
  322.         }  
  323.         if(hexStr.length()>0) {  
  324.             while(hexStr.length()<32) {  
  325.                 hexStr += "0";  
  326.             }  
  327.             sb.append(Tools.hexStr2Str(Tools.Cs2hexStr(inCipher(Tools.hexStr2Cs(hexStr),keys,round))));  
  328.         }  
  329.         while(sb.charAt(sb.length()-1) == 0) {  
  330.             sb = sb.deleteCharAt(sb.length()-1);  
  331.         }  
  332.         return sb.toString();  
  333.     }  
  334.     public String inCipher(String in) {  
  335.         return inCipher(in,this.key,this.round);  
  336.     }  
  337.     //行列变换  
  338.     public char[] exchange(char[] chars) {  
  339.         char[] nchars = new char[chars.length];  
  340.         for(int i=0; i<4; i++) {  
  341.             for(int j=0; j<4; j++) {  
  342.                 nchars[i*4 + j] = chars[j*4+i];  
  343.             }  
  344.         }  
  345.         return nchars;  
  346.     }  
  347.     public static void print(String s,char[] chars) {  
  348.         System.out.println(s+" ");  
  349.         String[] sts = Tools.Cs2Ss(chars);  
  350.         for(int i=0; i<sts.length; i++) {  
  351.             System.out.print(sts[i]+" ");  
  352.             if(i%4 == 3) {  
  353.                 System.out.println();  
  354.             }  
  355.         }  
  356.         System.out.println();  
  357.     }  
  358.     //密钥生成器  
  359.     public String key() {  
  360.         StringBuffer sb = new StringBuffer();  
  361.         Random r = new Random();  
  362.         for(int i=0; i<8; i++) {  
  363.             sb.append((char)r.nextInt(65535));  
  364.         }  
  365.         return Tools.Str2hexStr(sb.toString());  
  366.     }  
  367.     public static void main(String[] args) {  
  368.         AES aes = new AES();  
  369.         String cstring = "大家,, 爱上对方";  
  370.         //String cword = "2b7e151628aed2a6abf7158809cf4f3c";  
  371.         String cword= aes.key();  
  372.         String mw = aes.cipher(cstring);  
  373.         System.out.println("密文:    "+mw);  
  374.         String result1 = aes.inCipher(mw);  
  375.         System.out.println(result1);  
  376.         System.out.println("密钥:    "+cword);  
  377.     }  
  378. }  

 

 

工具类: MyMath

[java] view plaincopy
  1. package key;  
  2. import java.math.BigInteger;  
  3.   
  4.   
  5. public class MyMath {  
  6.     //此方法求余数。prime:素数,primitive:本原元,random:随机数。  
  7.     public static long reaminder(long prime, long primitive, long random) {  
  8.         long reamin = primitive%prime;  
  9.         long currentreamin = reamin;  
  10.         String binary = Long.toBinaryString(random);  
  11.         System.out.println(binary);  
  12.         for(int i=0; i<binary.length()-1; i++) {  
  13.             if(binary.charAt(i+1) == '0') {  
  14.                 currentreamin = (currentreamin * currentreamin) % prime;  
  15.             }  
  16.             else {  
  17.                 currentreamin = (currentreamin * currentreamin * reamin) % prime;  
  18.             }  
  19.               
  20.         }  
  21.         //  
  22.         /*if(random == 1) { 
  23.             return reamin; 
  24.         } 
  25.          
  26.         for(long i=2; i<=random; i++) { 
  27.             currentreamin = currentreamin * reamin % prime; 
  28.         }*/  
  29.         return currentreamin;  
  30.     }  
  31.     public static BigInteger reaminder(BigInteger prime, BigInteger primitive, long random) {  
  32.         BigInteger reamin = primitive.mod(prime);//primitive%prime;  
  33.         BigInteger currentreamin = reamin;  
  34.         String binary = Long.toBinaryString(random);  
  35.         for(int i=0; i<binary.length()-1; i++) {  
  36.             if(binary.charAt(i+1) == '0') {  
  37.                 currentreamin = currentreamin.multiply(currentreamin).mod(prime);//(currentreamin * currentreamin) % prime;  
  38.             }  
  39.             else {  
  40.                 currentreamin = currentreamin.multiply(currentreamin).multiply(reamin).mod(prime);//(currentreamin * currentreamin * reamin) % prime;  
  41.             }  
  42.               
  43.         }  
  44.         return currentreamin;  
  45.     }  
  46.     public static BigInteger reaminder(String prim, String primitiv, String rand) {  
  47.         BigInteger prime = new BigInteger(prim);  
  48.         BigInteger primitive = new BigInteger(primitiv);  
  49.         Long random = new Long(rand);  
  50.         BigInteger reamin = primitive.mod(prime);//primitive%prime;  
  51.         BigInteger currentreamin = reamin;  
  52.         String binary = Long.toBinaryString(random);  
  53.         for(int i=0; i<binary.length()-1; i++) {  
  54.             if(binary.charAt(i+1) == '0') {  
  55.                 currentreamin = currentreamin.multiply(currentreamin).mod(prime);//(currentreamin * currentreamin) % prime;  
  56.             }  
  57.             else {  
  58.                 currentreamin = currentreamin.multiply(currentreamin).multiply(reamin).mod(prime);//(currentreamin * currentreamin * reamin) % prime;  
  59.             }  
  60.               
  61.         }  
  62.         return currentreamin;  
  63.     }  
  64.       
  65.     //此方法判断素数  
  66.     public static boolean isPrime(long num) {  
  67.         boolean flag = true;  
  68.         for(long i=2; i<num/2; i++) {  
  69.             if(num == 2break;  
  70.             if(num%i == 0) {  
  71.                 flag = false;  
  72.                 break;  
  73.             }  
  74.         }  
  75.         return flag;  
  76.     }  
  77.       
  78.     //求最大公约数:欧几里得算法,辗转相除法  
  79.     public static long gcd(long a, long b) {  
  80.          long reamin = a % b;  
  81.          if(reamin==0) {  
  82.              return b;  
  83.          }  
  84.          else {  
  85.              return gcd(b,reamin);  
  86.          }  
  87.     }  
  88.       
  89.     //扩展的欧几里得算法求逆元,如果有返回值,没有返回-1  
  90.     public static long exgcd(long a, long b) {  
  91.         long x1=1,x2=0,x3=b,  
  92.              y1=0,y2=1,y3=a;  
  93.         while(true) {  
  94.             if(y3 == 0) {  
  95.                 return -1;  
  96.             }  
  97.             if(y3 == 1) {  
  98.                 return y2>0?y2:y2+b;  
  99.             }  
  100.             long t1,t2,t3;  
  101.             long q = x3/y3;  
  102.             t1 = x1-q*y1; t2 = x2 - q*y2; t3 = x3 - q*y3;  
  103.             x1 = y1; x2 = y2; x3 = y3;  
  104.             y1 = t1; y2 = t2; y3 = t3;  
  105.         }  
  106.     }  
  107.     public static BigInteger exgcd(BigInteger a, BigInteger b) {  
  108.         BigInteger x1=BigInteger.ONE,x2=BigInteger.ZERO,x3=b,  
  109.              y1=BigInteger.ZERO,y2=BigInteger.ONE,y3=a;  
  110.         while(true) {  
  111.             if(y3.equals(BigInteger.ZERO)) {  
  112.                 return BigInteger.ZERO.subtract(BigInteger.ONE);  
  113.             }  
  114.             if(y3.equals(BigInteger.ONE)) {  
  115.                 return y2;  
  116.             }  
  117.             BigInteger t1,t2,t3;  
  118.             BigInteger q = x3.divide(y3);//x3/y3;  
  119.             t1 = x1.subtract(q.multiply(y1));//x1-q*y1;   
  120.             t2 = x2.subtract(q.multiply(y2));//x2 - q*y2;   
  121.             t3 = x3.subtract(q.multiply(y3));//x3 - q*y3;  
  122.             x1 = y1; x2 = y2; x3 = y3;  
  123.             y1 = t1; y2 = t2; y3 = t3;  
  124.         }  
  125.     }  
  126.     public static void main(String[] args) {  
  127.         //System.out.println(exgcd(new BigInteger(5+""),new BigInteger(96+"")));  
  128.         //System.out.println((int)',');  
  129.         //System.out.println((char)(34382));  
  130.         //System.out.println(-19 % 96);  
  131.         //System.out.println(Character.getNumericValue('虎'));  
  132.         //System.out.println(reaminder("561","7","560"));  
  133.         //System.out.println(reaminder(561,7,560));  
  134.         //System.out.println(new BigInteger(7+"").modPow(new BigInteger("560"), new BigInteger("561")));  
  135.         //System.out.println(exgcd(-2,3));  
  136.         String a = "你好  好啊";  
  137.         //System.out.println((int)' ');  
  138.         char[] chars = a.toCharArray();  
  139.         for(int i=0; i<chars.length; i++) {  
  140.             String s = Integer.toHexString(chars[i]);  
  141.             s = Tools.obox(s, 4);  
  142.             System.out.println(s);  
  143.         }  
  144.     }  
  145. }  

 

 

工具类:Tools

[java] view plaincopy
  1. package key;  
  2.   
  3. public class Tools {  
  4.     //字符串左边补0直到长度为i  
  5.     public static String obox(String s, int i) {  
  6.         String ss = s;    
  7.         while(ss.length()<i) {  
  8.             ss = "0"+ss;  
  9.         }  
  10.         return ss;  
  11.     }  
  12.     //字符串右边补0直到长度为i  
  13.     public static String boxo(String s, int i) {  
  14.         String ss = s;    
  15.         while(ss.length()<i) {  
  16.             ss += "0";  
  17.         }  
  18.         return ss;  
  19.     }  
  20.     //将字符串变成16进制字符串  
  21.     public static String Str2hexStr(String s) {  
  22.         StringBuffer sb = new StringBuffer();  
  23.         for(int i=0; i<s.length(); i++) {  
  24.             sb.append(obox(Integer.toHexString(s.charAt(i)),4));  
  25.         }  
  26.         return sb.toString();  
  27.     }  
  28.     //将16进制字符串变成字符串  
  29.     public static String hexStr2Str(String s) {  
  30.         StringBuffer sb = new StringBuffer();  
  31.         int index = 0;  
  32.         int length = s.length();  
  33.         while(index+4 <= length) {  
  34.             String sh = s.substring(index, index+4);  
  35.             sb.append((char) Integer.parseInt(sh, 16));  
  36.             index += 4;  
  37.         }  
  38.         if(sb.charAt(sb.length()-1) == 0) {  
  39.             sb.deleteCharAt(sb.length()-1);  
  40.         }  
  41.         return sb.toString();  
  42.     }  
  43.     //String数组转换为char数组  
  44.     public static char[] Ss2Cs(String[] s) {  
  45.         char[] result = new char[s.length];  
  46.         for(int i=0; i<s.length; i++) {  
  47.             result[i] =(char) Integer.parseInt(s[i], 16);  
  48.         }  
  49.         return result;  
  50.     }  
  51.     //String转换为char数组  
  52.     public static char[] Str2Cs(String s) {  
  53.         char[] result = new char[s.length()/2];  
  54.         for(int i=0; i<s.length()/2; i++) {  
  55.             StringBuffer sb = new StringBuffer();//(char)s.charAt(i)+s.charAt(i+1);  
  56.             sb.append(s.charAt(i*2));sb.append(s.charAt(i*2+1));  
  57.             result[i] =(char) Integer.parseInt(sb.toString(), 16);  
  58.         }  
  59.         return result;  
  60.     }  
  61.     //hexString转换为数组  
  62.     public static char[] hexStr2Cs(String s) {  
  63.         //System.out.println("hexStr:" + s);  
  64.         char[] result = new char[s.length()/2];  
  65.         for(int i=0; i<s.length()/2; i++) {  
  66.             StringBuffer sb = new StringBuffer();//(char)s.charAt(i)+s.charAt(i+1);  
  67.             sb.append(s.charAt(i*2));  
  68.             sb.append(s.charAt(i*2+1));  
  69.             result[i] =(char) Integer.parseInt(sb.toString(), 16);  
  70.         }  
  71.         return result;  
  72.     }  
  73.     //char数组转换为String数组  
  74.     public static String[] Cs2Ss(char[] s) {  
  75.         String[] result = new String[s.length];  
  76.         for(int i=0; i<s.length; i++) {  
  77.             result[i] = Integer.toHexString(s[i]);  
  78.         }  
  79.         return result;  
  80.     }  
  81.     //char数组转换为hexString  
  82.     public static String Cs2hexStr(char[] s) {  
  83.         StringBuffer sb = new StringBuffer();  
  84.         //String[] result = new String[s.length];  
  85.         for(int i=0; i<s.length; i++) {  
  86.             sb.append(obox(Integer.toHexString(s[i]),2));  
  87.         }  
  88.         return sb.toString();  
  89.     }  
  90.     //long转换为hexString  
  91.     public static String long2hexStr(long lo) {  
  92.         //String s = Long.toHexString(lo);  
  93.         //s =   
  94.         return Long.toHexString(lo);  
  95.     }  
  96.     //longs数组转换为hexString  
  97.     public static String longs2hexStr(long[] lo) {  
  98.         StringBuffer sb = new StringBuffer();  
  99.         for(int i=0; i<lo.length; i++) {  
  100.             sb.append(Long.toHexString(lo[0]));  
  101.             sb.append(" ");  
  102.         }  
  103.         return sb.toString();  
  104.     }  
  105.     //hexString转换为long  
  106.     public static long hexStr2long(String s) {  
  107.         return Long.parseLong(s, 16);  
  108.     }  
  109.     //hexString转换为long数组  
  110.     public static long[] hexStr2longs(String s) {  
  111.         String[] ss = s.split(" ");  
  112.         long[] ls = new long[ss.length];  
  113.         for(int i=0; i<ls.length; i++) {  
  114.             ls[i] = Long.parseLong(ss[i], 16);  
  115.         }  
  116.         return ls;  
  117.     }  
  118.           
  119.     public static void main(String[] args) {  
  120.         String hexs1 = long2hexStr(Long.MAX_VALUE);  
  121.         String hexs2 = long2hexStr(456);  
  122.         String s = hexs1+" " +hexs2;  
  123.         System.out.println(s);  
  124.         long[] l = hexStr2longs(s);  
  125.         for(int i=0; i<l.length; i++)  
  126.             System.out.println(l[i]);  
  127.     }  
  128. }