RSA非对称加密和AES对称加密

代码是网上抄的,自己练练手

RSA加密

package com.answern.openplatform;

import org.apache.commons.codec.binary.Base64;
import org.junit.Test;


import javax.crypto.Cipher;
import java.io.File;
import java.math.BigInteger;
import java.nio.charset.Charset;
import java.security.*;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

/**
 *
    *--------------------------------------------**********--------------------------------------------
    *该算法于1977年由美国麻省理工学院MIT(Massachusetts Institute of Technology)的Ronal Rivest,Adi Shamir和Len Adleman三位年轻教授提出,并以三人的姓氏Rivest,Shamir和Adlernan命名为RSA算法,是一个支持变长密钥的公共密钥算法,需要加密的文件快的长度也是可变的!
    *所谓RSA加密算法,是世界上第一个非对称加密算法,也是数论的第一个实际应用。它的算法如下:
    *1.找两个非常大的质数p和q(通常p和q都有155十进制位或都有512十进制位)并计算n=pq,k=(p-1)(q-1)。
    *2.将明文编码成整数M,保证M不小于0但是小于n。
    *3.任取一个整数e,保证e和k互质,而且e不小于0但是小于k。加密钥匙(称作公钥)是(e,n)。
    *4.找到一个整数d,使得ed除以k的余数是1(只要e和n满足上面条件,d肯定存在)。解密钥匙(称作密钥)是(d,n)。
    *加密过程: 加密后的编码C等于M的e次方除以n所得的余数。
    *解密过程: 解密后的编码N等于C的d次方除以n所得的余数。
    *只要e、d和n满足上面给定的条件。M等于N。
    *--------------------------------------------**********--------------------------------------------

 * RAS  加密算法测试
 * @Author 冯浩
 * @Description
 * @Date: create in 15:14 2018/5/24
 * @Modified by
 */
public class RSATest {

    private final static int KEYSIZE = 1024;

    private final static String RSA = "RSA";

    public static final String RSA_ALGORITHM = "RSA/ECB/PKCS1Padding";


    public Map<String,Object> generotor() throws Exception{

        SecureRandom sr =new SecureRandom();
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(KEYSIZE,sr);

        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        Key pub = keyPair.getPublic();
        byte[] pubByte = pub.getEncoded();
        String publicKey = new String(pubByte,Charset.forName("UTF-8"));

        Key pri = keyPair.getPrivate();
        byte[] priByte = pri.getEncoded();
        String privateKey = new String(priByte,Charset.forName("UTF-8"));

        RSAPublicKey pubKey = (RSAPublicKey)keyPair.getPublic();
        BigInteger modulus = pubKey.getModulus();
        byte[] modulu = modulus.toByteArray();

        byte[] baseModulu = Base64.encodeBase64(modulu);
        String mo = new String(baseModulu,Charset.forName("UTF-8"));
        Map<String,Object> data = new HashMap<String,Object>();
        data.put("public",publicKey);
        data.put("private",privateKey);
        data.put("module",mo);
        return data;

    }

    /**
     * 获取公钥信息
     * @param key
     * @return
     * @throws Exception
     */
    public PublicKey getPublicKey(String key) throws Exception{
        X509EncodedKeySpec spec = new X509EncodedKeySpec(Base64.decodeBase64(key.getBytes()));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey publicKey = keyFactory.generatePublic(spec);
        return publicKey;
    }

    /**
     * 获取私钥信息
     * @param key
     * @return
     * @throws Exception
     */
    public PrivateKey getPrivateKey(String key) throws Exception{
        X509EncodedKeySpec spec = new X509EncodedKeySpec(Base64.decodeBase64(key.getBytes()));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = keyFactory.generatePrivate(spec);
        return privateKey;
    }

    /**
     * 加密
     * @param source
     * @param publicKey
     * @return
     * @throws Exception
     */
    public String encrypt(String source,String publicKey) throws Exception{
        Key key = getPublicKey(publicKey);
        Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE,key);
        byte[] bytes = source.getBytes();
        byte[] b = cipher.doFinal(bytes);
        return new String(b,Charset.forName("utf-8"));

    }

    /**
     * 解密
     * @param cypt
     * @param key
     * @return
     * @throws Exception
     */
    public String decrypt(String cypt,String key) throws Exception{
        Key privateKey = getPrivateKey(key);
        Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE,privateKey);
        byte[] so = Base64.decodeBase64(cypt.getBytes());
        byte[] b= cipher.doFinal(so);
        return new String(b);
    }

    /**
     * 生成签名
     * @param content
     * @param privateKey
     * @return
     * @throws Exception
     */
    public String sign(String content,String privateKey) throws Exception{
        String charset = "UTF-8";
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(content.getBytes()));
        KeyFactory keyFactory = KeyFactory.getInstance(RSA);
        PrivateKey priKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);

        Signature signature = Signature.getInstance("SHA1WithRSA");
        signature.initSign(priKey);
        signature.update(content.getBytes(charset));

        byte[] sign = signature.sign();

        return new String(Base64.encodeBase64(sign));
    }

    public void checkSign(String content,String sign,String publicKey) {
        try {

            KeyFactory keyFactory = KeyFactory.getInstance(RSA);
            byte[] decode = Base64.decodeBase64(publicKey);
            PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(decode));

            Signature signature = Signature.getInstance("SHA1WithRSA");

            signature.initVerify(pubKey);
            signature.update(content.getBytes("UTF-8"));

            boolean verify = signature.verify(Base64.decodeBase64(sign));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        RSATest test = new RSATest();
        int result = test.test();
        System.out.println(result);
    }

    public int test(){
        int a=1;
        try {

            return a++;
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            System.out.println("1"+a);
            return a++;
        }
    }

}    
View Code

AES加密

package com.answern.openplatform.app.utils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * @Author 冯浩
 * @Description
 * @Date: create in 17:06 2018/5/24
 * @Modified by
 */
public class AESUtils {

    public final static String AES = "AES";

    public static final String AES_ALGORITHM = "AES/ECB/PKCS5Padding";

    /**
     * 加密
     * @param data
     * @param key
     * @return
     */
    public static byte[] encrypt(byte[] data,byte[] key){
        if(key.length!=16){
            throw new RuntimeException("Invalid AES key length (must be 16 bytes)");
        }
        try {
            SecretKeySpec secretKeySpec = new SecretKeySpec(key,AES);
            byte[] bytes = secretKeySpec.getEncoded();
            SecretKeySpec secKey = new SecretKeySpec(bytes,AES);
            Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE,secKey);
            byte[] result = cipher.doFinal(data);
            return result;
        }catch (Exception e){
            throw new RuntimeException("encrypt fail!",e);
        }
    }

    /**
     * 解密
     * @param data
     * @param key
     * @return
     */
    public static byte[] decyypt(byte[] data,byte[] key){
        if(key.length!=16){
            throw new RuntimeException("Invalid AES key length (must be 16 bytes)");
        }
        try {
            SecretKeySpec secretKeySpec = new SecretKeySpec(key,AES);
            byte[] bytes = secretKeySpec.getEncoded();
            SecretKeySpec secKey = new SecretKeySpec(bytes,AES);
            Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE,secKey);
            byte[] result = cipher.doFinal(data);
            return result;
        }catch (Exception e){
            throw new RuntimeException("encrypt fail!",e);
        }
    }

    public static void main(String[] args) {
        String message = "大家";
        String key = "1111111111111111";
        byte[] result = AESUtils.encrypt(message.getBytes(),key.getBytes());

        System.out.println("***********************");
        byte[] abs = AESUtils.decyypt(result,key.getBytes());
        System.out.println(new String(abs));
    }

}    
View Code

猜你喜欢

转载自www.cnblogs.com/nihaofenghao/p/9090015.html