import java.io.IOException;

import java.security.InvalidKeyException;

import java.security.KeyFactory;

import java.security.KeyPair;

import java.security.KeyPairGenerator;

import java.security.NoSuchAlgorithmException;

import java.security.PrivateKey;

import java.security.PublicKey;

import java.security.Signature;

import java.security.SignatureException;

import java.security.spec.EncodedKeySpec;

import java.security.spec.InvalidKeySpecException;

import java.security.spec.PKCS8EncodedKeySpec;

import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;

import sun.misc.BASE64Decoder;

import sun.misc.BASE64Encoder;

/**

* RSA 签名、验证、加密、解密帮助类

*

* @author sam

*

*/

public class RsaHelper

{

// 签名对象

private Signature sign;

private static final RsaHelper rsaHelper = new RsaHelper();

private String pubkey;

private String prikey;

private RsaHelper()

{

try

{

sign = Signature.getInstance("SHA1withRSA");

}

catch (NoSuchAlgorithmException nsa)

{

System.out.println("" + nsa.getMessage());

}

}

public static RsaHelper getInstance()

{

return rsaHelper;

}

private PrivateKey getPrivateKey(String privateKeyStr)

{

try

{

byte[] privateKeyBytes = b64decode(privateKeyStr);

KeyFactory keyFactory = KeyFactory.getInstance("RSA");

EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);

return keyFactory.generatePrivate(privateKeySpec);

}

catch (InvalidKeySpecException e)

{

System.out.println("Invalid Key Specs. Not valid Key files." + e.getCause());

return null;

}

catch (NoSuchAlgorithmException e)

{

System.out.println("There is no such algorithm. Please check the JDK ver." + e.getCause());

return null;

}

}

private PublicKey getPublicKey(String publicKeyStr)

{

try

{

byte[] publicKeyBytes = b64decode(publicKeyStr);

KeyFactory keyFactory = KeyFactory.getInstance("RSA");

EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKeyBytes);

return keyFactory.generatePublic(publicKeySpec);

}

catch (InvalidKeySpecException e)

{

System.out.println("Invalid Key Specs. Not valid Key files." + e.getCause());

return null;

}

catch (NoSuchAlgorithmException e)

{

System.out.println("There is no such algorithm. Please check the JDK ver." + e.getCause());

return null;

}

}

/**

* RSA 数据签名

*

* @param toBeSigned

*            (待签名的原文)

* @param priKey

*            (RSA私钥)

* @return (返回RSA签名后的数据签名数据base64编码)

*/

public String signData(String toBeSigned, String priKey)

{

try

{

PrivateKey privateKey = getPrivateKey(priKey);

byte[] signByte = toBeSigned.getBytes("utf-8");

Signature rsa = Signature.getInstance("SHA1withRSA");

rsa.initSign(privateKey);

rsa.update(signByte);

return b64encode(rsa.sign());

}

catch (NoSuchAlgorithmException ex)

{

System.out.println(ex);

}

catch (InvalidKeyException in)

{

System.out.println("Invalid Key file.Please check the key file path" + in.getCause());

}

catch (Exception se)

{

System.out.println(se);

}

return null;

}

/**

* RSA 数据签名验证

*

* @param signature

*            (RSA签名数据(base64编码)

* @param data

*            (待验证的数据原文)

* @param pubKey

*            (RSA公钥数据)

* @return 返回验证结果(TRUE:验证成功;FALSE:验证失败)

*/

public boolean verifySignature(String signature, String data, String pubKey)

{

try

{

byte[] signByte = b64decode(signature);

byte[] dataByte = data.getBytes("utf-8");

PublicKey publicKey = getPublicKey(pubKey);

sign.initVerify(publicKey);

sign.update(dataByte);

return sign.verify(signByte);

}

catch (SignatureException e)

{

e.printStackTrace();

}

catch (Exception e)

{

e.printStackTrace();

}

return false;

}

/**

* base64编码

*

* @param data

* @return

*/

private String b64encode(byte[] data)

{

return new BASE64Encoder().encode(data);

}

/**

* base64解码

*

* @param data

* @return

*/

private byte[] b64decode(String data)

{

try

{

return new BASE64Decoder().decodeBuffer(data);

}

catch (Exception ex)

{

}

return null;

}

/**

* RSA数据加密

*

* @param data

*            (需要加密的数据)

* @param pubKey

*            (RSA公钥)

* @return 返回加密后的密文(BASE64编码)

*/

public String encryptData(String data, String pubKey)

{

try

{

byte[] dataByte = data.getBytes("utf-8");

PublicKey publicKey = getPublicKey(pubKey);

Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");

cipher.init(Cipher.ENCRYPT_MODE, publicKey);

return b64encode(cipher.doFinal(dataByte));

}

catch (Exception e)

{

return null;

}

}

/**

* RSA数据解密

*

* @param encryptedData

*            (需要解密的数据base64编码数据)

* @param priKey

*            (RSA的私钥)

* @return 返回解密后的原始明文

*/

public String decryptData(String encryptedData, String priKey)

{

try

{

byte[] encryData = b64decode(encryptedData);

PrivateKey privateKey = getPrivateKey(priKey);

Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");

cipher.init(Cipher.DECRYPT_MODE, privateKey);

return new String(cipher.doFinal(encryData), "utf-8");

}

catch (Exception e)

{

return null;

}

}

/**

* 得到私钥字符串(经过base64编码)

*

* @return

*/

public static String getPriKeyString(PrivateKey key) throws Exception

{

byte[] keyBytes = key.getEncoded();

String s = (new BASE64Encoder()).encode(keyBytes);

return s;

}

/**

* 得到公钥字符串(经过base64编码)

*

* @return

*/

public static String getPubKeyString(PublicKey key) throws Exception

{

byte[] keyBytes = key.getEncoded();

String s = (new BASE64Encoder()).encode(keyBytes);

return s;

}

/**

* 生成密钥 自动产生RSA1024位密钥

*

* @throws NoSuchAlgorithmException

* @throws IOException

*/

public void getAutoCreateRSA() throws NoSuchAlgorithmException, IOException

{

try

{

KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");

kpg.initialize(1024);

KeyPair kp = kpg.genKeyPair();

PublicKey puk = kp.getPublic();

PrivateKey prk = kp.getPrivate();

pubkey = getPubKeyString(puk);

prikey = getPriKeyString(prk);

System.out.print("pubkey==:"+pubkey.replaceAll("\r", "").replaceAll("\n", ""));

System.out.print("prikey==:"+prikey.replaceAll("\r", "").replaceAll("\n", ""));

}

catch (Exception e)

{

e.printStackTrace();

}

}

public String getPubkey()

{

return pubkey;

}

public void setPubkey(String pubkey)

{

this.pubkey = pubkey;

}

public String getPrikey()

{

return prikey;

}

public void setPrikey(String prikey)

{

this.prikey = prikey;

}

}

RSA 签名、验证、加密、解密帮助类的更多相关文章

  1. php加密解密功能类

    这两天突发奇想想要用php写一个对日常项目加密以及解密的功能,经过努力简单的封装了一个对php代码进行加密解密的类,一些思想也是来自于网络,初步测试用着还行,可以实现对指定项目的加密以及解密(只针对本 ...

  2. C# MD5加密解密帮助类

    /// <summary>    /// MD5加密解密帮助类    /// </summary>    public static class DESHelper    {  ...

  3. php加密解密处理类

    [PHP]代码 <?php /*=========================================================== = 版权协议: = GPL (The GN ...

  4. AES加密解密 助手类 CBC加密模式

    "; string result1 = AESHelper.AesEncrypt(str); string result2 = AESHelper.AesDecrypt(result1); ...

  5. .Net(c#)加密解密工具类:

    /// <summary> /// .Net加密解密帮助类 /// </summary> public class NetCryptoHelper { #region des实 ...

  6. Base64加密解密工具类

    使用Apache commons codec类Base64进行加密解密 maven依赖 <dependency> <groupId>commons-codec</grou ...

  7. ios RSA 验签加密解密

    关于公钥和私钥的生成,网上有很多本地生产的方法,我遇到的问题是,按照网上生产的方式生成7个文件,本地使用没有问题,但是和后台交互就不行了. 发现生成公钥和私钥的没有那么麻烦,使用在线生产工具就能使用, ...

  8. C#工具:加密解密帮助类

    using System; using System.IO; using System.Security.Cryptography; using System.Text; //加密字符串,注意strE ...

  9. java使用RSA与AES加密解密

    首先了解下,什么是堆成加密,什么是非对称加密? 对称加密:加密与解密的密钥是相同的,加解密速度很快,比如AES 非对称加密:加密与解密的秘钥是不同的,速度较慢,比如RSA 先看代码(先会用在研究) 相 ...

  10. PHP 服务端 和 APP 客户端 实现 RSA+AES 双向加密解密

    目的:服务端和移动端双向加密解密 共有七个文件 其中包括三个类文件 lib_aes.php aes对称加密解密类 server_rsa_crypt.php 服务端RSA公钥私钥非对称加密解密类 cli ...

随机推荐

  1. Linux 修改文件目录权限

    修改文件目录权限 chmod​ chmod u+x b.txt chmod 777 a.txt 修改文件的所有者和所属组 ​ 修改所有者chown beifeng a.txt 修改所属组chgrp b ...

  2. Django设置应用名与模型名为中文

    修改polls包里面的apps.py: from django.apps import AppConfig class PollsConfig(AppConfig): name = 'polls' v ...

  3. hexo利用SAE提高网页打开速度

    起因 之前一直觉得网页加载速度其实也还行,就是有两个图标加载的非常慢,经常是网页都出来了,那两个图标还是个方框,要等好久才出来.终于,好好研究了一番,发现那个图标是fontawesome里的,然后字体 ...

  4. requireJS的基本使用

    requireJS的基本使用 一.总结 一句话总结: requireJS是js端模块化开发,主要是实现js的异步加载,和管理模块之间的依赖关系,便于代码的编写和维护 1.页面加载的js文件过多的缺点是 ...

  5. DT资讯文章生成静态出现MySQL Error解决办法

    今天有个朋友的DT系统生成静态出现 MySQL Query:SELECT * FROM [pre]article_21 WHERE status=3 and itemid<>516548 ...

  6. css实现硬件加速

    原文请点击一下链接: http://blog.teamtreehouse.com/increase-your-sites-performance-with-hardware-accelerated-c ...

  7. js数组操作 求最大值,最小值,正序、倒叙大小值排序,去重复

    var arr = [1,5,2,56,12,34,21,3,5] Math.min.apply({},arr) Math.max.apply({},arr) arr.sort((m,n)=>m ...

  8. @getMapping和@postMapping,@RestController 区别

    @getMapping和@postMapping,@RestController   @RequestMapping   和  @GetMapping @PostMapping 区别 @GetMapp ...

  9. 全球百大最有前景AI公司出炉,中国成独角兽最强诞生地

    https://new.qq.com/omn/20190210/20190210B0BVK2.html 硅谷最强智库之一的 CB Insights 日前发布 AI 100 2019 报告,在这 100 ...

  10. 优雅关闭web服务的方式

    优雅关闭web服务 DBHelper, err = gorm.Open("mysql", "root:root@(115.159.59.129:3306)/test?ch ...