zoukankan      html  css  js  c++  java
  • JAVA加密

    【源地址http://www.iteye.com/topic/1122076/】

    加密,是以某种特殊的算法改变原有的信息数据,使得未授权的用户即使获得了已加密的信息,但因不知解密的方法,仍然无法了解信息的内容。大体上分为双向加密单向加密,而双向加密又分为对称加密非对称加密(有些资料将加密直接分为对称加密和非对称加密)。 

    双向加密大体意思就是明文加密后形成密文,可以通过算法还原成明文。而单向加密只是对信息进行了摘要计算,不能通过算法生成明文,单向加密从严格意思上说不能算是加密的一种,应该算是摘要算法吧。具体区分可以参考: 

    一、双向加密 
    (一)、对称加密 
    采用单钥密码系统的加密方法,同一个密钥可以同时用作信息的加密和解密,这种加密方法称为对称加密,也称为单密钥加密。 
    需要对加密和解密使用相同密钥的加密算法。由于其速度,对称性加密通常在消息发送方需要加密大量数据时使用。对称性加密也称为密钥加密。 
    所谓对称,就是采用这种加密方法的双方使用方式用同样的密钥进行加密和解密。密钥是控制加密及解密过程的指令。 

    算法是一组规则,规定如何进行加密和解密。因此对称式加密本身不是安全的。    
    常用的对称加密有:DES、IDEA、RC2、RC4、SKIPJACK、RC5、AES算法等 

    对称加密一般java类中中定义成员 

    //KeyGenerator 提供对称密钥生成器的功能,支持各种算法
    private KeyGenerator keygen;
    //SecretKey 负责保存对称密钥
    private SecretKey deskey;
    //Cipher负责完成加密或解密工作
    private Cipher c;
    //该字节数组负责保存加密的结果
    private byte[] cipherByte;
    

      在构造函数中初始化 

    Security.addProvider(new com.sun.crypto.provider.SunJCE());
    //实例化支持DES算法的密钥生成器(算法名称命名需按规定,否则抛出异常)
    keygen = KeyGenerator.getInstance("DES");//
    //生成密钥
    deskey = keygen.generateKey();
    //生成Cipher对象,指定其支持的DES算法
    c = Cipher.getInstance("DES");

    1. DES算法为密码体制中的对称密码体制,又被成为美国数据加密标准,是1972年美国IBM公司研制的对称密码体制加密算法。 明文按64位进行分组, 密钥长64位,密钥事实上是56位参与DES运算(第8、16、24、32、40、48、56、64位是校验位, 使得每个密钥都有奇数个1)分组后的明文组和56位的密钥按位替代或交换的方法形成密文组的加密方法。 

     1 import java.security.InvalidKeyException;
     2 import java.security.NoSuchAlgorithmException;
     3 import java.security.Security;
     4 
     5 import javax.crypto.BadPaddingException;
     6 import javax.crypto.Cipher;
     7 import javax.crypto.IllegalBlockSizeException;
     8 import javax.crypto.KeyGenerator;
     9 import javax.crypto.NoSuchPaddingException;
    10 import javax.crypto.SecretKey;
    11 
    12 public class EncrypDES {
    13     
    14     //KeyGenerator 提供对称密钥生成器的功能,支持各种算法
    15     private KeyGenerator keygen;
    16     //SecretKey 负责保存对称密钥
    17     private SecretKey deskey;
    18     //Cipher负责完成加密或解密工作
    19     private Cipher c;
    20     //该字节数组负责保存加密的结果
    21     private byte[] cipherByte;
    22     
    23     public EncrypDES() throws NoSuchAlgorithmException, NoSuchPaddingException{
    24         Security.addProvider(new com.sun.crypto.provider.SunJCE());
    25         //实例化支持DES算法的密钥生成器(算法名称命名需按规定,否则抛出异常)
    26         keygen = KeyGenerator.getInstance("DES");
    27         //生成密钥
    28         deskey = keygen.generateKey();
    29         //生成Cipher对象,指定其支持的DES算法
    30         c = Cipher.getInstance("DES");
    31     }
    32     
    33     /**
    34      * 对字符串加密
    35      * 
    36      * @param str
    37      * @return
    38      * @throws InvalidKeyException
    39      * @throws IllegalBlockSizeException
    40      * @throws BadPaddingException
    41      */
    42     public byte[] Encrytor(String str) throws InvalidKeyException,
    43             IllegalBlockSizeException, BadPaddingException {
    44         // 根据密钥,对Cipher对象进行初始化,ENCRYPT_MODE表示加密模式
    45         c.init(Cipher.ENCRYPT_MODE, deskey);
    46         byte[] src = str.getBytes();
    47         // 加密,结果保存进cipherByte
    48         cipherByte = c.doFinal(src);
    49         return cipherByte;
    50     }
    51 
    52     /**
    53      * 对字符串解密
    54      * 
    55      * @param buff
    56      * @return
    57      * @throws InvalidKeyException
    58      * @throws IllegalBlockSizeException
    59      * @throws BadPaddingException
    60      */
    61     public byte[] Decryptor(byte[] buff) throws InvalidKeyException,
    62             IllegalBlockSizeException, BadPaddingException {
    63         // 根据密钥,对Cipher对象进行初始化,DECRYPT_MODE表示加密模式
    64         c.init(Cipher.DECRYPT_MODE, deskey);
    65         cipherByte = c.doFinal(buff);
    66         return cipherByte;
    67     }
    68 
    69     /**
    70      * @param args
    71      * @throws NoSuchPaddingException 
    72      * @throws NoSuchAlgorithmException 
    73      * @throws BadPaddingException 
    74      * @throws IllegalBlockSizeException 
    75      * @throws InvalidKeyException 
    76      */
    77     public static void main(String[] args) throws Exception {
    78         EncrypDES de1 = new EncrypDES();
    79         String msg ="郭XX-搞笑相声全集";
    80         byte[] encontent = de1.Encrytor(msg);
    81         byte[] decontent = de1.Decryptor(encontent);
    82         System.out.println("明文是:" + msg);
    83         System.out.println("加密后:" + new String(encontent));
    84         System.out.println("解密后:" + new String(decontent));
    85     }
    86 
    87 }

    2. 3DES又称Triple DES,是DES加密算法的一种模式,它使用3条56位的密钥对3DES 
    数据进行三次加密。数据加密标准(DES)是美国的一种由来已久的加密标准,它使用对称密钥加密法,并于1981年被ANSI组织规范为ANSI X.3.92。DES使用56位密钥和密码块的方法,而在密码块的方法中,文本被分成64位大小的文本块然后再进行加密。比起最初的DES,3DES更为安全。    
    3DES(即Triple DES)是DES向AES过渡的加密算法(1999年,NIST将3-DES指定为过渡的加密标准),是DES的一个更安全的变形。它以DES为基本模块,通过组合分组方法设计出分组加密算法,其具体实现如下: 
    设Ek()和Dk()代表DES算法的加密和解密过程,K代表DES算法使用的密钥,P代表明文,C代表密文, 
    这样,    
    3DES加密过程为:C=Ek3(Dk2(Ek1(P))) 
    3DES解密过程为:P=Dk1((EK2(Dk3(C))) 

     1 import java.security.InvalidKeyException;
     2 import java.security.NoSuchAlgorithmException;
     3 import java.security.Security;
     4 
     5 import javax.crypto.BadPaddingException;
     6 import javax.crypto.Cipher;
     7 import javax.crypto.IllegalBlockSizeException;
     8 import javax.crypto.KeyGenerator;
     9 import javax.crypto.NoSuchPaddingException;
    10 import javax.crypto.SecretKey;
    11 
    12 public class EncrypDES3 {
    13 
    14     // KeyGenerator 提供对称密钥生成器的功能,支持各种算法
    15     private KeyGenerator keygen;
    16     // SecretKey 负责保存对称密钥
    17     private SecretKey deskey;
    18     // Cipher负责完成加密或解密工作
    19     private Cipher c;
    20     // 该字节数组负责保存加密的结果
    21     private byte[] cipherByte;
    22 
    23     public EncrypDES3() throws NoSuchAlgorithmException, NoSuchPaddingException {
    24         Security.addProvider(new com.sun.crypto.provider.SunJCE());
    25         // 实例化支持DES算法的密钥生成器(算法名称命名需按规定,否则抛出异常)
    26         keygen = KeyGenerator.getInstance("DESede");
    27         // 生成密钥
    28         deskey = keygen.generateKey();
    29         // 生成Cipher对象,指定其支持的DES算法
    30         c = Cipher.getInstance("DESede");
    31     }
    32 
    33     /**
    34      * 对字符串加密
    35      * 
    36      * @param str
    37      * @return
    38      * @throws InvalidKeyException
    39      * @throws IllegalBlockSizeException
    40      * @throws BadPaddingException
    41      */
    42     public byte[] Encrytor(String str) throws InvalidKeyException,
    43             IllegalBlockSizeException, BadPaddingException {
    44         // 根据密钥,对Cipher对象进行初始化,ENCRYPT_MODE表示加密模式
    45         c.init(Cipher.ENCRYPT_MODE, deskey);
    46         byte[] src = str.getBytes();
    47         // 加密,结果保存进cipherByte
    48         cipherByte = c.doFinal(src);
    49         return cipherByte;
    50     }
    51 
    52     /**
    53      * 对字符串解密
    54      * 
    55      * @param buff
    56      * @return
    57      * @throws InvalidKeyException
    58      * @throws IllegalBlockSizeException
    59      * @throws BadPaddingException
    60      */
    61     public byte[] Decryptor(byte[] buff) throws InvalidKeyException,
    62             IllegalBlockSizeException, BadPaddingException {
    63         // 根据密钥,对Cipher对象进行初始化,DECRYPT_MODE表示加密模式
    64         c.init(Cipher.DECRYPT_MODE, deskey);
    65         cipherByte = c.doFinal(buff);
    66         return cipherByte;
    67     }
    68 
    69     /**
    70      * @param args
    71      * @throws NoSuchPaddingException 
    72      * @throws NoSuchAlgorithmException 
    73      * @throws BadPaddingException 
    74      * @throws IllegalBlockSizeException 
    75      * @throws InvalidKeyException 
    76      */
    77     public static void main(String[] args) throws Exception {
    78         EncrypDES3 des = new EncrypDES3();
    79         String msg ="郭XX-搞笑相声全集";
    80         byte[] encontent = des.Encrytor(msg);
    81         byte[] decontent = des.Decryptor(encontent);
    82         System.out.println("明文是:" + msg);
    83         System.out.println("加密后:" + new String(encontent));
    84         System.out.println("解密后:" + new String(decontent));
    85 
    86     }
    87 
    88 }

    3. AES密码学中的高级加密标准(Advanced Encryption Standard,AES),又称  高级加密标准 
    Rijndael加密法,是美国联邦政府采用的一种区块加密标准。这个标准用来替代原先的DES,已经被多方分析且广为全世界所使用。经过五年的甄选流程,高级加密标准由美国国家标准与技术研究院(NIST)于2001年11月26日发布于FIPS PUB 197,并在2002年5月26日成为有效的标准。2006年,高级加密标准已然成为对称密钥加密中最流行的算法之一。   该算法为比利时密码学家Joan Daemen和Vincent Rijmen所设计,结合两位作者的名字,以Rijndael之命名之,投稿高级加密标准的甄选流程。(Rijdael的发音近于 "Rhinedoll"。) 

     1 import java.security.InvalidKeyException;
     2 import java.security.NoSuchAlgorithmException;
     3 import java.security.Security;
     4 
     5 import javax.crypto.BadPaddingException;
     6 import javax.crypto.Cipher;
     7 import javax.crypto.IllegalBlockSizeException;
     8 import javax.crypto.KeyGenerator;
     9 import javax.crypto.NoSuchPaddingException;
    10 import javax.crypto.SecretKey;
    11 
    12 public class EncrypAES {
    13     
    14     //KeyGenerator 提供对称密钥生成器的功能,支持各种算法
    15     private KeyGenerator keygen;
    16     //SecretKey 负责保存对称密钥
    17     private SecretKey deskey;
    18     //Cipher负责完成加密或解密工作
    19     private Cipher c;
    20     //该字节数组负责保存加密的结果
    21     private byte[] cipherByte;
    22     
    23     public EncrypAES() throws NoSuchAlgorithmException, NoSuchPaddingException{
    24         Security.addProvider(new com.sun.crypto.provider.SunJCE());
    25         //实例化支持DES算法的密钥生成器(算法名称命名需按规定,否则抛出异常)
    26         keygen = KeyGenerator.getInstance("AES");
    27         //生成密钥
    28         deskey = keygen.generateKey();
    29         //生成Cipher对象,指定其支持的DES算法
    30         c = Cipher.getInstance("AES");
    31     }
    32     
    33     /**
    34      * 对字符串加密
    35      * 
    36      * @param str
    37      * @return
    38      * @throws InvalidKeyException
    39      * @throws IllegalBlockSizeException
    40      * @throws BadPaddingException
    41      */
    42     public byte[] Encrytor(String str) throws InvalidKeyException,
    43             IllegalBlockSizeException, BadPaddingException {
    44         // 根据密钥,对Cipher对象进行初始化,ENCRYPT_MODE表示加密模式
    45         c.init(Cipher.ENCRYPT_MODE, deskey);
    46         byte[] src = str.getBytes();
    47         // 加密,结果保存进cipherByte
    48         cipherByte = c.doFinal(src);
    49         return cipherByte;
    50     }
    51 
    52     /**
    53      * 对字符串解密
    54      * 
    55      * @param buff
    56      * @return
    57      * @throws InvalidKeyException
    58      * @throws IllegalBlockSizeException
    59      * @throws BadPaddingException
    60      */
    61     public byte[] Decryptor(byte[] buff) throws InvalidKeyException,
    62             IllegalBlockSizeException, BadPaddingException {
    63         // 根据密钥,对Cipher对象进行初始化,DECRYPT_MODE表示加密模式
    64         c.init(Cipher.DECRYPT_MODE, deskey);
    65         cipherByte = c.doFinal(buff);
    66         return cipherByte;
    67     }
    68 
    69     /**
    70      * @param args
    71      * @throws NoSuchPaddingException 
    72      * @throws NoSuchAlgorithmException 
    73      * @throws BadPaddingException 
    74      * @throws IllegalBlockSizeException 
    75      * @throws InvalidKeyException 
    76      */
    77     public static void main(String[] args) throws Exception {
    78         EncrypAES de1 = new EncrypAES();
    79         String msg ="郭XX-搞笑相声全集";
    80         byte[] encontent = de1.Encrytor(msg);
    81         byte[] decontent = de1.Decryptor(encontent);
    82         System.out.println("明文是:" + msg);
    83         System.out.println("加密后:" + new String(encontent));
    84         System.out.println("解密后:" + new String(decontent));
    85     }
    86 
    87 }

    (二)、非对称加密 
    1976年,美国学者Dime和Henman为解决信息公开传送和密钥管理问题,提出一种新的密钥交换协议,允许在不安全的媒体上的通讯双方交换信息,安全地达成一致的密钥,这就是“公开密钥系统”。相对于“对称加密算法”这种方法也叫做“非对称加密算法”。 与对称加密算法不同,非对称加密算法需要两个密钥:公开密钥(publickey)和私有密钥 
    (privatekey)。公开密钥与私有密钥是一对,如果用公开密钥对数据进行加密,只有用对应的私有密钥才能解密;如果用私有密钥对数据进行加密,那么只有用对应的公开密钥才能解密。因为加密和解密使用的是两个不同的密钥,所以这种算法叫作非对称加密算法。 

    1. RSA 公钥加密算法是1977年由Ron Rivest、Adi Shamirh和LenAdleman在(美国麻省理工学院)开发的。RSA取名来自开发他们三者的名字。RSA是目前最有影响力的公钥加密算法,它能够抵抗到目前为止已知的所有密码攻击,已被ISO推荐为公钥数据加密标准。RSA算法基于一个十分简单的数论事实:将两个大素数相乘十分容易,但那时想要对其乘积进行因式分解却极其困难,因此可以将乘积公开作为加密密钥。

     1 import java.security.InvalidKeyException;
     2 import java.security.KeyPair;
     3 import java.security.KeyPairGenerator;
     4 import java.security.NoSuchAlgorithmException;
     5 import java.security.interfaces.RSAPrivateKey;
     6 import java.security.interfaces.RSAPublicKey;
     7 
     8 import javax.crypto.BadPaddingException;
     9 import javax.crypto.Cipher;
    10 import javax.crypto.IllegalBlockSizeException;
    11 import javax.crypto.NoSuchPaddingException;
    12 
    13 public class EncrypRSA {
    14     
    15     /**
    16      * 加密
    17      * @param publicKey
    18      * @param srcBytes
    19      * @return
    20      * @throws NoSuchAlgorithmException
    21      * @throws NoSuchPaddingException
    22      * @throws InvalidKeyException
    23      * @throws IllegalBlockSizeException
    24      * @throws BadPaddingException
    25      */
    26     protected byte[] encrypt(RSAPublicKey publicKey,byte[] srcBytes) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException{
    27         if(publicKey!=null){
    28             //Cipher负责完成加密或解密工作,基于RSA
    29             Cipher cipher = Cipher.getInstance("RSA");
    30             //根据公钥,对Cipher对象进行初始化
    31             cipher.init(Cipher.ENCRYPT_MODE, publicKey);
    32             byte[] resultBytes = cipher.doFinal(srcBytes);
    33             return resultBytes;
    34         }
    35         return null;
    36     }
    37     
    38     /**
    39      * 解密 
    40      * @param privateKey
    41      * @param srcBytes
    42      * @return
    43      * @throws NoSuchAlgorithmException
    44      * @throws NoSuchPaddingException
    45      * @throws InvalidKeyException
    46      * @throws IllegalBlockSizeException
    47      * @throws BadPaddingException
    48      */
    49     protected byte[] decrypt(RSAPrivateKey privateKey,byte[] srcBytes) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException{
    50         if(privateKey!=null){
    51             //Cipher负责完成加密或解密工作,基于RSA
    52             Cipher cipher = Cipher.getInstance("RSA");
    53             //根据公钥,对Cipher对象进行初始化
    54             cipher.init(Cipher.DECRYPT_MODE, privateKey);
    55             byte[] resultBytes = cipher.doFinal(srcBytes);
    56             return resultBytes;
    57         }
    58         return null;
    59     }
    60 
    61     /**
    62      * @param args
    63      * @throws NoSuchAlgorithmException 
    64      * @throws BadPaddingException 
    65      * @throws IllegalBlockSizeException 
    66      * @throws NoSuchPaddingException 
    67      * @throws InvalidKeyException 
    68      */
    69     public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
    70         EncrypRSA rsa = new EncrypRSA();
    71         String msg = "郭XX-精品相声";
    72         //KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象
    73         KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
    74         //初始化密钥对生成器,密钥大小为1024位
    75         keyPairGen.initialize(1024);
    76         //生成一个密钥对,保存在keyPair中
    77         KeyPair keyPair = keyPairGen.generateKeyPair();
    78         //得到私钥
    79         RSAPrivateKey privateKey = (RSAPrivateKey)keyPair.getPrivate();                
    80         //得到公钥
    81         RSAPublicKey publicKey = (RSAPublicKey)keyPair.getPublic();
    82         
    83         //用公钥加密
    84         byte[] srcBytes = msg.getBytes();
    85         byte[] resultBytes = rsa.encrypt(publicKey, srcBytes);
    86         
    87         //用私钥解密
    88         byte[] decBytes = rsa.decrypt(privateKey, resultBytes);
    89         
    90         System.out.println("明文是:" + msg);
    91         System.out.println("加密后是:" + new String(resultBytes));
    92         System.out.println("解密后是:" + new String(decBytes));
    93     }
    94 
    95 }

    2. DSA 
    Digital Signature Algorithm (DSA)是Schnorr和ElGamal签名算法的变种,被美国NIST作为DSS(DigitalSignature Standard)。 简单的说,这是一种更高级的验证方式,用作数字签名。不单单只有公钥、私钥,还有数字签名。私钥加密生成数字签名,公钥验证数据及签名。如果数据和签名不匹配则认为验证失败!也就是说传输中的数据可以不再加密,接收方获得数据后,拿到公钥与签名比对数据是否有效! 

     代码参照:http://63938525.iteye.com/blog/1051565

  • 相关阅读:
    python 发邮件乱码
    膳魔师杯使用注意事项
    了解指针,分分钟的事情 C++筆記--指針
    海淘攻略
    【转】Cocos2dx.3x入门三部曲
    在Windows7上搭建Cocos2d-x 3.2alpha0开发环境
    黑苹果 MAC OS X 10.10.2 安装流程
    Linux 下如何查找木马并处理
    js如何判断访问是来自搜索引擎(蜘蛛人)还是直接访问
    泰*网 Centos 一些命令
  • 原文地址:https://www.cnblogs.com/HansonYao/p/JAVA_Encrypt.html
Copyright © 2011-2022 走看看