教学服务系统

 找回密码
 立即注册
搜索
查看: 597|回复: 2

信息计算2019级1班1号原野

[复制链接]

10

主题

19

帖子

106

积分

注册会员

Rank: 2

积分
106
发表于 2022-5-30 23:13:55 | 显示全部楼层 |阅读模式

ECC椭圆曲线加密


1.简介:ECC 是 Elliptic Curves Cryptography 的缩写,属于公开密钥算法,意为椭圆曲线编码编码学。ECC的主要优势是在某些情况下它比其他的方法使用更小的密钥——比如RSA加密算法——提供相当的或更高等级的安全,可以用较少的计算能力提供比RSA加密算法更高的安全强度,有效地解决了“提高安全强度必须增加密钥长度”的工程实现问题。ECC的另一个优势是可以定义群之间的双线性映射,基于Weil对或是Tate对;双线性映射已经在密码学中发现了大量的应用,例如基于身份的加密。不过一个缺点是加密和解密操作的实现比其他机制花费的时间长。

2.原理: 椭圆曲线 K=kG,其中K,G为Ep(a,b)上的点,k为小于n的整数,n是点G的阶,设K为公钥,k为私钥,G为基点。   
加密过程: A选定一条椭圆曲线Ep(a,b),并取曲线上一点作为基点G ;A选择一个私钥k,并生成公钥K=kG ,A将Ep(a,b)和k,G发送给B,B收到后将明文编码到Ep(a,b)上一点M,并产生一个随机数r ;B计算点C1=M+rK,C2=rG ;B将C1,C2传给A ;A计算C1-kC2=M+rkG-krG=M ;A对M解码得到明文;攻击者只能得到Ep(a,b),G,K,C1,C2,没有k就无法得到M。
3.代码:
  1. package tttt;
  2. import java.security.KeyFactory;  
  3. import java.security.KeyPair;  
  4. import java.security.KeyPairGenerator;  
  5. import java.security.PrivateKey;  
  6. import java.security.PublicKey;  
  7. import java.security.SecureRandom;  
  8. import java.security.Security;  
  9. import java.security.spec.PKCS8EncodedKeySpec;  
  10. import java.security.spec.X509EncodedKeySpec;  
  11.   
  12. import javax.crypto.Cipher;  
  13.   
  14. import org.bouncycastle.jce.interfaces.ECPrivateKey;  
  15. import org.bouncycastle.jce.interfaces.ECPublicKey;
  16. import org.springframework.util.Base64Utils;  
  17.   
  18.   
  19. public class test {  
  20.     static {  
  21.         Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());  
  22.     }  
  23.       
  24.     //生成秘钥对  
  25.     public static KeyPair getKeyPair() throws Exception {  
  26.         KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC", "BC");  
  27.         keyPairGenerator.initialize(256, new SecureRandom());  
  28.         KeyPair keyPair = keyPairGenerator.generateKeyPair();  
  29.         return keyPair;  
  30.     }  
  31.       
  32.     //获取公钥(Base64编码)  
  33.     public static String getPublicKey(KeyPair keyPair){  
  34.         ECPublicKey publicKey = (ECPublicKey) keyPair.getPublic();  
  35.         byte[] bytes = publicKey.getEncoded();  
  36.         return Base64Utils.encodeToString(bytes);  
  37.     }  
  38.       
  39.     //获取私钥(Base64编码)  
  40.     public static String getPrivateKey(KeyPair keyPair){  
  41.         ECPrivateKey privateKey = (ECPrivateKey) keyPair.getPrivate();  
  42.         byte[] bytes = privateKey.getEncoded();  
  43.         return Base64Utils.encodeToString(bytes);  
  44.     }  
  45.       
  46.     //将Base64编码后的公钥转换成PublicKey对象  
  47.     public static ECPublicKey string2PublicKey(String pubStr) throws Exception{  
  48.         byte[] keyBytes = Base64Utils.decodeFromString(pubStr);  
  49.         X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);  
  50.         KeyFactory keyFactory = KeyFactory.getInstance("EC", "BC");  
  51.         ECPublicKey publicKey = (ECPublicKey) keyFactory.generatePublic(keySpec);  
  52.         return publicKey;  
  53.     }  
  54.       
  55.     //将Base64编码后的私钥转换成PrivateKey对象  
  56.     public static ECPrivateKey string2PrivateKey(String priStr) throws Exception{  
  57.         byte[] keyBytes = Base64Utils.decodeFromString(priStr);
  58.         PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);  
  59.         KeyFactory keyFactory = KeyFactory.getInstance("EC", "BC");  
  60.         ECPrivateKey privateKey = (ECPrivateKey) keyFactory.generatePrivate(keySpec);  
  61.         return privateKey;  
  62.     }  
  63.       
  64.     //公钥加密  
  65.     public static byte[] publicEncrypt(byte[] content, PublicKey publicKey) throws Exception{  
  66.         Cipher cipher = Cipher.getInstance("ECIES", "BC");  
  67.         cipher.init(Cipher.ENCRYPT_MODE, publicKey);  
  68.         byte[] bytes = cipher.doFinal(content);  
  69.         return bytes;  
  70.     }  
  71.       
  72.     //私钥解密  
  73.     public static byte[] privateDecrypt(byte[] content, PrivateKey privateKey) throws Exception{  
  74.         Cipher cipher = Cipher.getInstance("ECIES", "BC");  
  75.         cipher.init(Cipher.DECRYPT_MODE, privateKey);  
  76.         byte[] bytes = cipher.doFinal(content);  
  77.         return bytes;  
  78.     }  
  79.       
  80.     public static void main(String[] args) throws Exception {  
  81.         KeyPair keyPair = test.getKeyPair();  
  82.         String publicKeyStr = test.getPublicKey(keyPair);  
  83.         String privateKeyStr = test.getPrivateKey(keyPair);  
  84.         System.out.println("ECC公钥Base64编码:" + publicKeyStr);  
  85.         System.out.println("ECC私钥Base64编码:" + privateKeyStr);  
  86.          
  87.         ECPublicKey publicKey = string2PublicKey(publicKeyStr);  
  88.         ECPrivateKey privateKey = string2PrivateKey(privateKeyStr);  
  89.          
  90.         byte[] publicEncrypt = publicEncrypt("Hello World!".getBytes(), publicKey);  
  91.         String encodeToString = Base64Utils.encodeToString(publicEncrypt);
  92.         System.out.println(encodeToString);
  93.         byte[] privateDecrypt = privateDecrypt(publicEncrypt, privateKey);  
  94.         System.out.println(new String(privateDecrypt));  
  95.     }  
  96. }  
复制代码


回复

使用道具 举报

10

主题

19

帖子

106

积分

注册会员

Rank: 2

积分
106
 楼主| 发表于 2022-5-31 09:49:27 | 显示全部楼层
本帖最后由 1班1号原野 于 2022-5-31 09:55 编辑

RSA加密算法
1.介绍:RSA算法是非对称加密算法,这种算法非常可靠,密钥越长,它就越难破解(本质上是对大数的质因数分解很难),非对称加密是通过两个密钥(公钥-私钥)来实现对数据的加密和解密的。公钥用于加密,私钥用于解密。
2.原理:
(1)公钥与密钥的产生:假设A想接收B的讯息,先产生公钥和一个私钥:获取N: 随意选择两个大的质数p和q,p不等于q,计算N=pq;获取r: 根据欧拉函数r = φ(N) = φ§φ(q) = (p-1)(q-1);选择一个小于 r 的整数 e,求得 e 关于模 r 的模反元素,命名为d。(模反元素存在,当且仅当e与r互质,即求 e^(φ®-1) )。(N,e)是公钥,(N,d)是私钥。A将她的公钥(N,e)传给B,私钥(N,d)自己保存。
(2)加密消息:假设B想给A送一个消息,他知道A产生的公钥(N,e)。 于是B先将消息转换为一个小于N的整数m。(如果是字符串可以取ascii值或unicode值;假如信息非常长,可以将分为几段,然后将每一段转换为m) 他可以将m加密为c:m^e ≡ c (mod N),B算出c后就可以将它传递给A。
(3)解密消息:A得到B的消息c后就可以利用她的密钥(N, d)来解码。将c转换为m:c^d ≡ m (mod N);得到m后,她就可以将原来的信息重新复原。
3.优缺点:
优点:1.不需要进行密钥传递,提高了安全性 2.可以进行数字签名认证。缺点:1.加密解密效率不高,一般只适用于处理小量数据(如:密钥)2.容易遭受小指数攻击
4.代码:
(1)test类

  1. package tttt;

  2. import java.io.BufferedReader;
  3. import java.io.IOException;
  4. import java.io.InputStreamReader;
  5. import java.math.BigInteger;

  6. public class test {

  7.         /**
  8.          * @param args
  9.          */
  10.         private final static BigInteger flag=new BigInteger("1");
  11.         private final static BigInteger p=new BigInteger("9183437365667304713151339115533307748437632107328003875473596831166621217151099398895985502248093628101123702365666975004854482171521309873216481517187327");
  12.         private final static BigInteger q=new BigInteger("7029820695008441957065724311434977975249823906050830354649892478269625322133288476430275975540723696853422938582813278061763348125218857806738991220864067");
  13.         
  14.         private static BigInteger privatekey;
  15.         private static BigInteger publickey;
  16.         private BigInteger n;             //大素数n
  17.         private BigInteger pn;            //n的欧拉值
  18.         private BigInteger d,temp;
  19.         int j;
  20.         
  21.         test()
  22.         {
  23.                 n=p.multiply(q);              //n=p*q;
  24.                 System.out.println("n="+n);
  25.                 pn=(p.subtract(flag)).multiply(q.subtract(flag));  //pn=(p-1)*(q-1)
  26.                
  27.                 temp=pn.subtract(flag);       //从pn-1开始向下寻找publickey
  28.                 do
  29.                 {
  30.                         temp=temp.subtract(flag);
  31.                         d=temp.gcd(pn);                  //temp与pn的最大公因数
  32.                         j=d.intValue();
  33.                 }while(j!=1);                      //当最大公因数为1时,找到publickey
  34.                
  35.                 publickey=temp;
  36.                 System.out.println("publickey="+publickey);
  37.                 privatekey=temp.modInverse(pn);    //私钥pivatekey*publickey mod pn=1
  38.         }
  39.         
  40.         BigInteger modPow(BigInteger base,BigInteger exponent,BigInteger modules)  //运算函数
  41.         {
  42.                 BigInteger result=new BigInteger("0");
  43.                 if(base.compareTo(new BigInteger("0"))==0)
  44.                         return result;
  45.                 else
  46.                         if(exponent.compareTo(new BigInteger("0"))==0)
  47.                                 return flag;
  48.                         else
  49.                                 if(exponent.compareTo(new BigInteger("1"))==0)
  50.                                         return base.mod(modules);
  51.                                 else
  52.                                 {
  53.                                         result=modPow((base.multiply(base)).mod(modules),exponent.divide(new BigInteger("2")),modules);
  54.                                         if(exponent.mod(new BigInteger("2")).compareTo(flag)!=0)
  55.                                                 return result;
  56.                                         else
  57.                                                 return result.multiply(base).mod(modules);
  58.                                 }        
  59.         }        
  60.         
  61.         BigInteger encrypt_normal(BigInteger message)  //加密过程
  62.         {
  63.                 return modPow(message,publickey, n);
  64.         }
  65.         BigInteger decrypt_normal(BigInteger message)  //解密过程
  66.         {
  67.                 return modPow(message,privatekey,n);
  68.         }
  69.         BigInteger encrypt_quick(BigInteger message)
  70.         {
  71.                
  72.                 String pub_key=publickey.toString(2);
  73.                 BigInteger result;
  74.                 BigInteger temp=message;
  75.                 int i,length=pub_key.length();
  76.                 if((pub_key.charAt(length-1))=='0')
  77.                         result=flag;
  78.                 else
  79.                         result=message;
  80.                 for(i=length-2;i>=0;i--)
  81.                 {
  82.                         temp=(temp.multiply(temp)).mod(n);
  83.                         if(pub_key.charAt(i)=='1')
  84.                                 result=(result.multiply(temp)).mod(n);
  85.                 }
  86.                 return result;
  87.         }
  88.         BigInteger decrypt_quick(BigInteger message)
  89.         {
  90.                
  91.                 String pub_key=privatekey.toString(2);
  92.                 BigInteger result;
  93.                 BigInteger temp=message;
  94.                 int i,length=pub_key.length();
  95.                 if((pub_key.charAt(length-1))=='0')
  96.                         result=flag;
  97.                 else
  98.                         result=message;
  99.                 for(i=length-2;i>=0;i--)
  100.                 {
  101.                         temp=(temp.multiply(temp)).mod(n);
  102.                         if(pub_key.charAt(i)=='1')
  103.                                 result=(result.multiply(temp)).mod(n);
  104.                 }
  105.                 return result;
  106.         }
  107. }
复制代码










回复

使用道具 举报

10

主题

19

帖子

106

积分

注册会员

Rank: 2

积分
106
 楼主| 发表于 2022-5-31 09:52:09 | 显示全部楼层
接上一条RSA算法代码
(2)oo类
  1. package tttt;

  2. import javax.swing.*;
  3. import java.awt.*;
  4. import java.awt.event.*;
  5. import java.io.IOException;
  6. import java.math.BigInteger;

  7. public class oo extends JFrame  
  8. {
  9.         test test=new test();
  10.        
  11.         protected JButton button_en=new JButton("加密");
  12.         protected JButton button_de=new JButton("解密");
  13.         protected JButton button_exit=new JButton("退出");
  14.         protected JLabel    label1=new JLabel("    明文     ");
  15.         protected JLabel    label2=new JLabel("加密结果 ");
  16.         protected JLabel    label5=new JLabel("解密结果 ");
  17.         protected JLabel    label3=new JLabel(" 时间开销(秒)");
  18.         protected JLabel    label4=new JLabel("      加脱密方式");
  19.         protected JLabel    label6=new JLabel("注意:实验明文输入不能超过128个字符,否则解密会乱码");
  20.         protected JPanel    panel1=new JPanel();
  21.         protected JPanel    panel2=new JPanel();
  22.         protected JPanel    panel3=new JPanel();
  23.         protected JPanel    panel4=new JPanel();
  24.         protected JPanel    panel5=new JPanel();
  25.         protected JPanel    panel6=new JPanel();
  26.         protected GridBagLayout glo1=new GridBagLayout();
  27.         protected GridBagConstraints c = new GridBagConstraints();
  28.         protected GridLayout glo2=new GridLayout(3,3,3,3);
  29.         protected FlowLayout glo3=new FlowLayout();

  30.         protected JRadioButton jr_button1=new JRadioButton("    快速方式");
  31.         protected JRadioButton jr_button2=new JRadioButton("    一般方式");

  32.         protected JTextField textfield1=new JTextField(22);
  33.         protected JTextField textfield2=new JTextField(22);
  34.         protected JTextField textfield3=new JTextField(5);
  35.         protected JTextField textfield4=new JTextField(5);
  36.         protected JTextField textfield5=new JTextField(22);
  37.        
  38.         protected boolean method=false;                                  //默认加密模式一般方式
  39.         String mt,mm,str;
  40.         BigInteger en,result,message;
  41.         byte[] bc=new byte[10000];
  42.         byte[] by=new byte[10000];

  43.         Container container=getContentPane();
  44.         EventHandler handler=new EventHandler();
  45.         EventHandler1 handler1=new EventHandler1();
  46.        
  47.         oo()
  48.         {
  49.                 super("test加脱密系统");

  50.                 container.add(panel1);
  51.                 panel1.setLayout(glo3);
  52.                        
  53.         panel1.add(panel2);
  54.                 panel2.setLayout(glo1);
  55.                 c.fill = GridBagConstraints.BOTH; //在水平方向和垂直方向上同时调整组件大小
  56.                 c.weightx = 1.0;
  57.                 panel2.add(label1,c);
  58.                 panel2.add(textfield1,c);
  59.                 textfield1.setForeground(Color.RED);
  60.             textfield1.setBackground(Color.WHITE);

  61.                 panel1.add(panel4);
  62.                 panel4.setLayout(glo1);
  63.                 panel4.add(label2,c);
  64.                 panel4.add(textfield2,c);
  65.                 textfield2.setForeground(Color.RED);
  66.             textfield2.setBackground(Color.WHITE);
  67.             
  68.             panel1.add(panel5);
  69.                 panel5.setLayout(glo1);
  70.                 panel5.add(label5,c);
  71.                 panel5.add(textfield5,c);
  72.                 textfield5.setForeground(Color.RED);
  73.             textfield5.setBackground(Color.WHITE);

  74.         panel1.add(panel3);
  75.                 panel3.setLayout(glo2);
  76.                 panel3.add(label4);
  77.                 panel3.add(label3);
  78.                 panel3.add(button_en);
  79.                 panel3.add(jr_button1);
  80.                 panel3.add(textfield3);
  81.                 textfield3.setForeground(Color.BLUE);
  82.             textfield3.setBackground(Color.WHITE);
  83.                 panel3.add(button_de);
  84.                 panel3.add(jr_button2);
  85.                 panel3.add(textfield4);
  86.                 textfield4.setForeground(Color.BLUE);
  87.             textfield4.setBackground(Color.WHITE);
  88.                 panel3.add(button_exit);
  89.                
  90.                 panel1.add(panel6);
  91.                 panel6.add(label6);
  92.                
  93.                 button_en.addActionListener(handler);        //button调用事件处理类
  94.                 button_de.addActionListener(handler);      
  95.                 button_exit.addActionListener(handler);        
  96.                 jr_button1.addActionListener(handler1);     
  97.                 jr_button2.addActionListener(handler1);        

  98.                 setSize(330,250);
  99.                 setVisible(true);               
  100.                 setResizable(false);                    // 不能用鼠标拉伸窗体

  101.         }
  102.         class EventHandler1 implements ActionListener
  103.         {
  104.                 public void actionPerformed(ActionEvent event)
  105.                 {
  106.                         JRadioButton jcheck=(JRadioButton)event.getSource(); //获取发生event的对象
  107.                         if(jcheck==jr_button1)
  108.                         {
  109.                                 method=false;                                     //选择快速加密方式
  110.                            jr_button1.setSelected(true);
  111.                            jr_button2.setSelected(false);
  112.                         }
  113.                     if(jcheck==jr_button2)
  114.                     {
  115.                             method=true;                                     //选择一般加密方式
  116.                             jr_button2.setSelected(true);
  117.                             jr_button1.setSelected(false);
  118.                     }
  119.                 }
  120.         }
  121.         class EventHandler implements ActionListener             //自建一个事件处理类,内部嵌套类
  122.         {
  123.                 public void actionPerformed(ActionEvent event)       //实现接口中的actionPerformed方法
  124.                 {
  125.                         JButton check=(JButton)event.getSource();         
  126.                     if(check==button_en)
  127.                     {
  128.                             str=textfield1.getText();
  129.                             System.out.println("需加密信息="+str);                           
  130.                             try
  131.                             {
  132.                                 String str1=java.net.URLEncoder.encode(str,"utf-8");  //对汉字进行处理,避免解密时乱码
  133.                                 by=str1.getBytes();                   //将读入信息转化为字节数组
  134.                             }catch(IOException e)
  135.                             {
  136.                                     e.printStackTrace();
  137.                             }                                                                  
  138.                                 message=new BigInteger(by);               //将转化的字节数组变成大数表示
  139.                             if(method)
  140.                             {
  141.                                     long t1 = System.nanoTime();
  142.                                     for(int i=0;i<10;i++)
  143.                                     {
  144.                                             en=test.encrypt_normal(message);
  145.                                     }
  146.                                     long t2 = System.nanoTime();
  147.                                 mt=(en.toString(16)).toUpperCase();
  148.                                 textfield2.setText(mt);
  149.                                 long anverage_time=(t2-t1)/10;
  150.                                 Float time=new Float(anverage_time/(float)1000000000);       //加密10次的平均时间
  151.                                 textfield4.setText(time.toString());
  152.                             }
  153.                             else
  154.                             {
  155.                                     long t1=System.nanoTime();
  156.                                     for(int i=0;i<10;i++)
  157.                                     {
  158.                                             en=test.encrypt_quick(message);
  159.                                     }
  160.                                     long t2=System.nanoTime();
  161.                                     mm=(en.toString(16)).toUpperCase();
  162.                                 textfield2.setText(mm);
  163.                                 long anverage_time=(t2-t1)/10;
  164.                                 Float time=new Float(anverage_time/(float)1000000000);       //加密10次的平均时间
  165.                                 textfield3.setText(time.toString());;
  166.                             }
  167.                                    
  168.                     }                           
  169.                     
  170.                     if(check==button_de)
  171.                     {
  172.                             if(method)
  173.                             {
  174.                                     result=test.decrypt_normal(en);
  175.                                     str=result.toString();                            //解密结果由大数转化为数字字符串
  176.                                     bc=result.toByteArray();                          //将字符串转化为字节数组
  177.                                     String x=new String(bc);                          //将字节数组转化为字符串
  178.                                     try{
  179.                                         String y=java.net.URLDecoder.decode(x,"utf-8");        //汉字处理
  180.                                         textfield5.setText(y);
  181.                                     }catch(IOException e)
  182.                                     {
  183.                                             e.printStackTrace();
  184.                                     }                                   
  185.                             }
  186.                             else
  187.                             {
  188.                                     result=test.decrypt_quick(en);
  189.                                     str=result.toString();                            //解密结果由大数转化为数字字符串
  190.                                     bc=result.toByteArray();                          //将字符串转化为字节数组
  191.                                     String x=new String(bc);                          //将字节数组转化为字符串
  192.                                     try{
  193.                                         String y=java.net.URLDecoder.decode(x,"utf-8");        //汉字处理
  194.                                         textfield5.setText(y);
  195.                                     }catch(IOException e)
  196.                                     {
  197.                                             e.printStackTrace();
  198.                                     }                    
  199.                             }
  200.                     }
  201.                     if(check==button_exit)       
  202.                     {
  203.                             System.exit(0);
  204.                     }
  205.                 }
  206.         }
  207.         public static void main(String[] args)
  208.         {
  209.                 oo oo=new oo();
  210.                 oo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  211.         }
  212. }
复制代码
5.截图:

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有帐号?立即注册

x
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

教学服务系统

GMT+8, 2025-4-30 07:49 , Processed in 0.019399 second(s), 19 queries .

Powered by Discuz! X3.4

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表