Java 第三方android rsa公钥加密 RSA加密求助

关于JAVA中RSA加签解签,私钥加密公钥解密和公钥加密私钥解密代码步骤_Java编程-织梦者
当前位置:&>&&>& > 关于JAVA中RSA加签解签,私钥加密公钥解密和公钥加密私钥解密代码步骤
关于JAVA中RSA加签解签,私钥加密公钥解密和公钥加密私钥解密代码步骤
在项目中遇到的问题百度了许久总结出来的 私钥加密公钥解密和公钥加密私钥解密。
一般为了安全采用的是私钥加密,公钥解密(公钥可以用Base64转换后公开)
package com.paic.mon.
import java.security.KeyF
import java.security.MessageD
import java.security.PrivateK
import java.security.PublicK
import java.security.S
import java.security.KeyP
import java.security.KeyPairG
import java.security.SecureR
import java.security.spec.PKCS8EncodedKeyS
import java.security.spec.X509EncodedKeyS
import java.util.A
import javax.crypto.C
import mons.codec.binary.Base64;
* 封装同RSA非对称加密算法有关的方法,可用于数字签名,RSA加密解密
* @Copyright:WDSsoft
public class RSATool {
public RSATool() {
/**使用私钥加密数据
* 用一个已打包成byte[]形式的私钥加密数据,即数字签名
* @param keyInByte
* 打包成byte[]的私钥
* @param source
* 要签名的数据,一般应是数字摘要
* @return 签名 byte[]
public static byte[] sign(byte[] keyInByte, byte[] source) {
PKCS8EncodedKeySpec priv_spec = new PKCS8EncodedKeySpec(keyInByte);
KeyFactory mykeyFactory = KeyFactory.getInstance(&RSA&);
PrivateKey privKey = mykeyFactory.generatePrivate(priv_spec);
Signature sig = Signature.getInstance(&SHA1withRSA&);
sig.initSign(privKey);
sig.update(source);
return sig.sign();
} catch (Exception e) {
* 验证数字签名
* @param keyInByte
* 打包成byte[]形式的公钥
* @param source
* 原文的数字摘要
* @param sign
* 签名(对原文的数字摘要的签名)
* @return 是否证实 boolean
public static boolean verify(byte[] keyInByte, byte[] source, byte[] sign) {
KeyFactory mykeyFactory = KeyFactory.getInstance(&RSA&);
Signature sig = Signature.getInstance(&SHA1withRSA&);
X509EncodedKeySpec pub_spec = new X509EncodedKeySpec(keyInByte);
PublicKey pubKey = mykeyFactory.generatePublic(pub_spec);
sig.initVerify(pubKey);
sig.update(source);
return sig.verify(sign);
} catch (Exception e) {
* 建立新的密钥对,返回打包的byte[]形式私钥和公钥
* @return 包含打包成byte[]形式的私钥和公钥的object[],其中,object[0]为私钥byte[],object[1]为公钥byte[]
public static Object[] giveRSAKeyPairInByte() {
KeyPair newKeyPair = creatmyKey();
if (newKeyPair == null)
Object[] re = new Object[2];
if (newKeyPair != null) {
PrivateKey priv = newKeyPair.getPrivate();
byte[] b_priv = priv.getEncoded();
PublicKey pub = newKeyPair.getPublic();
byte[] b_pub = pub.getEncoded();
re[0] = b_
re[1] = b_
* 新建密钥对
* @return KeyPair对象
public static KeyPair creatmyKey() {
KeyPair myP
mySeed = System.currentTimeMillis();
KeyPairGenerator keyGen = KeyPairGenerator.getInstance(&RSA&);
SecureRandom random = SecureRandom.getInstance(&SHA1PRNG&, &SUN&);
random.setSeed(mySeed);
keyGen.initialize(1024, random);
myPair = keyGen.generateKeyPair();
} catch (Exception e1) {
return myP
* 使用RSA公钥加密数据
* @param pubKeyInByte
* 打包的byte[]形式公钥
* @param data
* 要加密的数据
* @return 加密数据
public static byte[] encryptByRSA(byte[] pubKeyInByte, byte[] data) {
KeyFactory mykeyFactory = KeyFactory.getInstance(&RSA&);
X509EncodedKeySpec pub_spec = new X509EncodedKeySpec(pubKeyInByte);
PublicKey pubKey = mykeyFactory.generatePublic(pub_spec);
Cipher cipher = Cipher.getInstance(&RSA/ECB/PKCS1Padding&);
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
return cipher.doFinal(data);
} catch (Exception e) {
* 用RSA私钥解密
* @param privKeyInByte
* 私钥打包成byte[]形式
* @param data
* 要解密的数据
* @return 解密数据
public static byte[] decryptByRSA(byte[] privKeyInByte, byte[] data) {
PKCS8EncodedKeySpec priv_spec = new PKCS8EncodedKeySpec(
privKeyInByte);
KeyFactory mykeyFactory = KeyFactory.getInstance(&RSA&);
PrivateKey privKey = mykeyFactory.generatePrivate(priv_spec);
Cipher cipher = Cipher.getInstance(&RSA/ECB/PKCS1Padding&);
cipher.init(Cipher.DECRYPT_MODE, privKey);
return cipher.doFinal(data);
} catch (Exception e) {
* 使用RSA私钥加密数据
* @param pubKeyInByte
* 打包的byte[]形式私钥
* @param data
* 要加密的数据
* @return 加密数据
public static byte[] encryptByRSA1(byte[] privKeyInByte, byte[] data) {
PKCS8EncodedKeySpec priv_spec = new PKCS8EncodedKeySpec(
privKeyInByte);
KeyFactory mykeyFactory = KeyFactory.getInstance(&RSA&);
PrivateKey privKey = mykeyFactory.generatePrivate(priv_spec);
Cipher cipher = Cipher.getInstance(mykeyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, privKey);
return cipher.doFinal(data);
} catch (Exception e) {
* 用RSA公钥解密
* @param privKeyInByte
* 公钥打包成byte[]形式
* @param data
* 要解密的数据
* @return 解密数据
public static byte[] decryptByRSA1(byte[] pubKeyInByte, byte[] data) {
KeyFactory mykeyFactory = KeyFactory.getInstance(&RSA&);
X509EncodedKeySpec pub_spec = new X509EncodedKeySpec(pubKeyInByte);
PublicKey pubKey = mykeyFactory.generatePublic(pub_spec);
Cipher cipher = Cipher.getInstance(mykeyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, pubKey);
return cipher.doFinal(data);
} catch (Exception e) {
* 计算字符串的SHA数字摘要,以byte[]形式返回
public static byte[] MdigestSHA(String source) {
//byte[] nullreturn = { 0 };
MessageDigest thisMD = MessageDigest.getInstance(&SHA&);
byte[] digest = thisMD.digest(source.getBytes(&UTF-8&));
} catch (Exception e) {
public static void main(String[] args) {
//私钥加密 公钥解密
//生成私钥-公钥对
Object[] v = giveRSAKeyPairInByte();
//获得摘要
byte[] source =MdigestSHA(&假设这是要加密的客户数据&);
//使用私钥对摘要进行加密 获得密文 即数字签名
byte[] sign = sign((byte[]) v[0], source);
//使用公钥对密文进行解密,解密后与摘要进行匹配
boolean yes = verify((byte[]) v[1], source, sign);
System.out.println(&匹配成功 合法的签名!&);
//公钥加密私钥解密
//获得摘要
byte[] sourcepub_pri = (&||||public&).getBytes(&UTF-8&);
//使用公钥对摘要进行加密 获得密文
byte[] signpub_pri =encryptByRSA((byte[]) v[1] ,sourcepub_pri);
//System.out.println(&公钥加密密文:&+new String(Base64.encodeBase64(signpub_pri)));
//使用私钥对密文进行解密 返回解密后的数据
byte[] newSourcepub_pri=decryptByRSA((byte[]) v[0],signpub_pri);
System.out.println(&私钥解密:&+new String(newSourcepub_pri,&UTF-8&));
//对比源数据与解密后的数据
if(Arrays.equals(sourcepub_pri, newSourcepub_pri))
System.out.println(&匹配成功 合法的私钥!&);
//私钥加密公钥解密
//获得摘要
//byte[] sourcepri_pub = MdigestSHA(&假设这是要加密的客户数据&);
byte[] sourcepri_pub = (&||||private&).getBytes(&UTF-8&);
//使用私钥对摘要进行加密 获得密文
byte[] signpri_pub =encryptByRSA1((byte[]) v[0] ,sourcepri_pub);
// System.out.println(&私钥加密密文:&+new String(Base64.encodeBase64(sign11)));
//使用公钥对密文进行解密 返回解密后的数据
byte[] newSourcepri_pub=decryptByRSA1((byte[]) v[1],signpri_pub);
System.out.println(&公钥解密:&+new String(newSourcepri_pub,&UTF-8&));
String PUBLICKEY=&MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCEGENnf3rdiO20isoLQqezw12FoWXII9FBw8nR1MWQ3X0CVzOsqY1hOmxD/YI9OB7WVIaVax5tj1l+wk6A0v85Z4OpGWqz4B5L3fCUlBwf/M6DXHlSN1OZttvQF3OeWvc6gvJHihR7pp18zc4KfCJx0Ry6IrGH/2SNOVE1AIgvRQIDAQAB&;
String PRIVATEKEY=&MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAIQYQ2d/et2I7bSKygtCp7PDXYWhZcgj0UHDydHUxZDdfQJXM6ypjWE6bEP9gj04HtZUhpVrHm2PWX7CToDS/zlng6kZarPgHkvd8JSUHB/8zoNceVI3U5m229AXc55a9zqC8keKFHumnXzNzgp8InHRHLoisYf/ZI05UTUAiC9FAgMBAAECgYAGNcHNds/G5G4QY8n1149cwx19b8YCL7Thu5ucUr1q/w6mcoUKY/oyjPWUCLH7wMyqVNTy51NJ4UhazjW0lrbK4ZbPDHFij9CiZ7QFASiQ/TQWaL+KSIWnE6/rK9IdouwFKxk+cvvLteZoAXP6mFcrsa7LzfkENiIMu7mjpTNHAQJBANXv9U5JWOAVhWHDQcEWKn7YKpAVRleXdeUeJrXcdkqBDI+P6suA9j+ahDREfu+x65wUsrJotPHUXgJG0TarJIUCQQCeEPLrv6Qvi5+nbn2Eifn/fjsmIdI0U2WZKDHWJEnLsRUuGDNYxVE/SPDNDedA2OHeFB6j0Kk/ECdsWnUq6zvBAkAgUGViFMwa1MVX1fFZo+p5TFdpef0s/9Cr8djxAULQ0BtAmAFkCa+oPcOYTXxK4jnvUmUHc69ZE7W7bEzvj/wtAkB50X4mClAzBFxK4XCC0QOG0HYtcStbgFpwqvWdn+Hvxc4Y9DW+WHPBXimXHvv2ki+gw8jJX2rQW1bGvwBFz30BAkASPkORJxVWv91StjI2f/HXDO5eG5/su/XIb3eajaLUSEdaQlcs3ywLrrJ0o3VAR0J9aq59cmp6em017AMnmbF7&;
byte[] signPrivate=Base64.decodeBase64(PRIVATEKEY.getBytes());
byte[] signPublic=Base64.decodeBase64(PUBLICKEY.getBytes());
String publicpwd =&N/b4nYbbLFVq0yTAIOpNNydtNQUCQxQy0B7bD6kzxLMW2guYxXtWOC/9Z5dpWecx/y7d5CezUJ6cf/8++msiNie4DcKBaFDFPh5rPbjeEB+DRfhjcdR2BsVGXWLsq3dLYLgZObQXG6Tb9rXakuH34Y+6KIIwCjiODH2QAU+PSiM=&;
String privatepwd =&MTMyNjU5ODY1ODR8fDMxNjQ5NDY0NjU0NjQ4NjQ5OHx8MDF8fHByaXZhdGU=&;
//使用私钥对密文进行解密 返回解密后的数据
byte[] newSource111=decryptByRSA(signPrivate,Base64.decodeBase64(publicpwd.getBytes()));
System.out.println(&私钥解密1:&+new String(newSource111,&UTF-8&));
} catch (Exception e) {
e.printStackTrace();
运行结果:
匹配成功 合法的签名!
私钥解密:||||public
匹配成功 合法的私钥!
公钥解密:||||private
私钥解密1:||||
以上就是关于JAVA中RSA加签解签,私钥加密公钥解密和公钥加密私钥解密代码步骤的全文介绍,希望对您学习和使用java程序开发有所帮助.
这些内容可能对你也有帮助
更多可查看Java编程列表页。
猜您也会喜欢这些文章81763人阅读
算法(22)
由于项目要用到非对称加密解密签名校验什么的,于是参考《Java加密解密的艺术》写一个RSA进行加密解密签名及校验的Demo,代码很简单,特此分享!RSA加密解密类:package com.
import java.io.BufferedR
import java.io.BufferedW
import java.io.FileR
import java.io.FileW
import java.io.IOE
import java.security.InvalidKeyE
import java.security.KeyF
import java.security.KeyP
import java.security.KeyPairG
import java.security.NoSuchAlgorithmE
import java.security.SecureR
import java.security.interfaces.RSAPrivateK
import java.security.interfaces.RSAPublicK
import java.security.spec.InvalidKeySpecE
import java.security.spec.PKCS8EncodedKeyS
import java.security.spec.X509EncodedKeyS
import javax.crypto.BadPaddingE
import javax.crypto.C
import javax.crypto.IllegalBlockSizeE
import javax.crypto.NoSuchPaddingE
import com.fcplay.Base64;
public class RSAEncrypt {
* 字节数据转字符串专用集合
private static final char[] HEX_CHAR = { '0', '1', '2', '3', '4', '5', '6',
'7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
* 随机生成密钥对
public static void genKeyPair(String filePath) {
// KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象
KeyPairGenerator keyPairGen =
keyPairGen = KeyPairGenerator.getInstance(&RSA&);
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
// 初始化密钥对生成器,密钥大小为96-1024位
keyPairGen.initialize(1024,new SecureRandom());
// 生成一个密钥对,保存在keyPair中
KeyPair keyPair = keyPairGen.generateKeyPair();
// 得到私钥
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
// 得到公钥
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
// 得到公钥字符串
String publicKeyString = Base64.encode(publicKey.getEncoded());
// 得到私钥字符串
String privateKeyString = Base64.encode(privateKey.getEncoded());
// 将密钥对写入到文件
FileWriter pubfw = new FileWriter(filePath + &/publicKey.keystore&);
FileWriter prifw = new FileWriter(filePath + &/privateKey.keystore&);
BufferedWriter pubbw = new BufferedWriter(pubfw);
BufferedWriter pribw = new BufferedWriter(prifw);
pubbw.write(publicKeyString);
pribw.write(privateKeyString);
pubbw.flush();
pubbw.close();
pubfw.close();
pribw.flush();
pribw.close();
prifw.close();
} catch (Exception e) {
e.printStackTrace();
* 从文件中输入流中加载公钥
* @param in
公钥输入流
* @throws Exception
加载公钥时产生的异常
public static String loadPublicKeyByFile(String path) throws Exception {
BufferedReader br = new BufferedReader(new FileReader(path
+ &/publicKey.keystore&));
String readLine =
StringBuilder sb = new StringBuilder();
while ((readLine = br.readLine()) != null) {
sb.append(readLine);
br.close();
return sb.toString();
} catch (IOException e) {
throw new Exception(&公钥数据流读取错误&);
} catch (NullPointerException e) {
throw new Exception(&公钥输入流为空&);
* 从字符串中加载公钥
* @param publicKeyStr
公钥数据字符串
* @throws Exception
加载公钥时产生的异常
public static RSAPublicKey loadPublicKeyByStr(String publicKeyStr)
throws Exception {
byte[] buffer = Base64.decode(publicKeyStr);
KeyFactory keyFactory = KeyFactory.getInstance(&RSA&);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
return (RSAPublicKey) keyFactory.generatePublic(keySpec);
} catch (NoSuchAlgorithmException e) {
throw new Exception(&无此算法&);
} catch (InvalidKeySpecException e) {
throw new Exception(&公钥非法&);
} catch (NullPointerException e) {
throw new Exception(&公钥数据为空&);
* 从文件中加载私钥
* @param keyFileName
私钥文件名
* @return 是否成功
* @throws Exception
public static String loadPrivateKeyByFile(String path) throws Exception {
BufferedReader br = new BufferedReader(new FileReader(path
+ &/privateKey.keystore&));
String readLine =
StringBuilder sb = new StringBuilder();
while ((readLine = br.readLine()) != null) {
sb.append(readLine);
br.close();
return sb.toString();
} catch (IOException e) {
throw new Exception(&私钥数据读取错误&);
} catch (NullPointerException e) {
throw new Exception(&私钥输入流为空&);
public static RSAPrivateKey loadPrivateKeyByStr(String privateKeyStr)
throws Exception {
byte[] buffer = Base64.decode(privateKeyStr);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
KeyFactory keyFactory = KeyFactory.getInstance(&RSA&);
return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
} catch (NoSuchAlgorithmException e) {
throw new Exception(&无此算法&);
} catch (InvalidKeySpecException e) {
throw new Exception(&私钥非法&);
} catch (NullPointerException e) {
throw new Exception(&私钥数据为空&);
* 公钥加密过程
* @param publicKey
* @param plainTextData
* @throws Exception
加密过程中的异常信息
public static byte[] encrypt(RSAPublicKey publicKey, byte[] plainTextData)
throws Exception {
if (publicKey == null) {
throw new Exception(&加密公钥为空, 请设置&);
Cipher cipher =
// 使用默认RSA
cipher = Cipher.getInstance(&RSA&);
// cipher= Cipher.getInstance(&RSA&, new BouncyCastleProvider());
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] output = cipher.doFinal(plainTextData);
} catch (NoSuchAlgorithmException e) {
throw new Exception(&无此加密算法&);
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
throw new Exception(&加密公钥非法,请检查&);
} catch (IllegalBlockSizeException e) {
throw new Exception(&明文长度非法&);
} catch (BadPaddingException e) {
throw new Exception(&明文数据已损坏&);
* 私钥加密过程
* @param privateKey
* @param plainTextData
* @throws Exception
加密过程中的异常信息
public static byte[] encrypt(RSAPrivateKey privateKey, byte[] plainTextData)
throws Exception {
if (privateKey == null) {
throw new Exception(&加密私钥为空, 请设置&);
Cipher cipher =
// 使用默认RSA
cipher = Cipher.getInstance(&RSA&);
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
byte[] output = cipher.doFinal(plainTextData);
} catch (NoSuchAlgorithmException e) {
throw new Exception(&无此加密算法&);
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
throw new Exception(&加密私钥非法,请检查&);
} catch (IllegalBlockSizeException e) {
throw new Exception(&明文长度非法&);
} catch (BadPaddingException e) {
throw new Exception(&明文数据已损坏&);
* 私钥解密过程
* @param privateKey
* @param cipherData
* @return 明文
* @throws Exception
解密过程中的异常信息
public static byte[] decrypt(RSAPrivateKey privateKey, byte[] cipherData)
throws Exception {
if (privateKey == null) {
throw new Exception(&解密私钥为空, 请设置&);
Cipher cipher =
// 使用默认RSA
cipher = Cipher.getInstance(&RSA&);
// cipher= Cipher.getInstance(&RSA&, new BouncyCastleProvider());
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] output = cipher.doFinal(cipherData);
} catch (NoSuchAlgorithmException e) {
throw new Exception(&无此解密算法&);
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
throw new Exception(&解密私钥非法,请检查&);
} catch (IllegalBlockSizeException e) {
throw new Exception(&密文长度非法&);
} catch (BadPaddingException e) {
throw new Exception(&密文数据已损坏&);
* 公钥解密过程
* @param publicKey
* @param cipherData
* @return 明文
* @throws Exception
解密过程中的异常信息
public static byte[] decrypt(RSAPublicKey publicKey, byte[] cipherData)
throws Exception {
if (publicKey == null) {
throw new Exception(&解密公钥为空, 请设置&);
Cipher cipher =
// 使用默认RSA
cipher = Cipher.getInstance(&RSA&);
// cipher= Cipher.getInstance(&RSA&, new BouncyCastleProvider());
cipher.init(Cipher.DECRYPT_MODE, publicKey);
byte[] output = cipher.doFinal(cipherData);
} catch (NoSuchAlgorithmException e) {
throw new Exception(&无此解密算法&);
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
throw new Exception(&解密公钥非法,请检查&);
} catch (IllegalBlockSizeException e) {
throw new Exception(&密文长度非法&);
} catch (BadPaddingException e) {
throw new Exception(&密文数据已损坏&);
* 字节数据转十六进制字符串
* @param data
* @return 十六进制内容
public static String byteArrayToString(byte[] data) {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i & data. i++) {
// 取出字节的高四位 作为索引得到相应的十六进制标识符 注意无符号右移
stringBuilder.append(HEX_CHAR[(data[i] & 0xf0) &&& 4]);
// 取出字节的低四位 作为索引得到相应的十六进制标识符
stringBuilder.append(HEX_CHAR[(data[i] & 0x0f)]);
if (i & data.length - 1) {
stringBuilder.append(' ');
return stringBuilder.toString();
签名及校验类:package com.
import java.security.KeyF
import java.security.PrivateK
import java.security.PublicK
import java.security.spec.PKCS8EncodedKeyS
import java.security.spec.X509EncodedKeyS
* RSA签名验签类
public class RSASignature{
* 签名算法
public static final String SIGN_ALGORITHMS = &SHA1WithRSA&;
* @param content 待签名数据
* @param privateKey 商户私钥
* @param encode 字符集编码
* @return 签名值
public static String sign(String content, String privateKey, String encode)
PKCS8EncodedKeySpec priPKCS8
= new PKCS8EncodedKeySpec( Base64.decode(privateKey) );
KeyFactory keyf
= KeyFactory.getInstance(&RSA&);
PrivateKey priKey
= keyf.generatePrivate(priPKCS8);
java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
signature.initSign(priKey);
signature.update( content.getBytes(encode));
byte[] signed = signature.sign();
return Base64.encode(signed);
catch (Exception e)
e.printStackTrace();
public static String sign(String content, String privateKey)
PKCS8EncodedKeySpec priPKCS8
= new PKCS8EncodedKeySpec( Base64.decode(privateKey) );
KeyFactory keyf = KeyFactory.getInstance(&RSA&);
PrivateKey priKey = keyf.generatePrivate(priPKCS8);
java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
signature.initSign(priKey);
signature.update( content.getBytes());
byte[] signed = signature.sign();
return Base64.encode(signed);
catch (Exception e)
e.printStackTrace();
* RSA验签名检查
* @param content 待签名数据
* @param sign 签名值
* @param publicKey 分配给开发商公钥
* @param encode 字符集编码
* @return 布尔值
public static boolean doCheck(String content, String sign, String publicKey,String encode)
KeyFactory keyFactory = KeyFactory.getInstance(&RSA&);
byte[] encodedKey = Base64.decode(publicKey);
PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
java.security.Signature signature = java.security.Signature
.getInstance(SIGN_ALGORITHMS);
signature.initVerify(pubKey);
signature.update( content.getBytes(encode) );
boolean bverify = signature.verify( Base64.decode(sign) );
catch (Exception e)
e.printStackTrace();
public static boolean doCheck(String content, String sign, String publicKey)
KeyFactory keyFactory = KeyFactory.getInstance(&RSA&);
byte[] encodedKey = Base64.decode(publicKey);
PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
java.security.Signature signature = java.security.Signature
.getInstance(SIGN_ALGORITHMS);
signature.initVerify(pubKey);
signature.update( content.getBytes() );
boolean bverify = signature.verify( Base64.decode(sign) );
catch (Exception e)
e.printStackTrace();
再来一个Base64的类,当然你也可以用commons-codec-1.9.jarpackage com.
public final class Base64 {
static private final int
BASELENGTH
static private final int
LOOKUPLENGTH
static private final int
TWENTYFOURBITGROUP
static private final int
static private final int
SIXTEENBIT
static private final int
static private final int
static private final char
static private final boolean fDebug
static final private byte[]
base64Alphabet
= new byte[BASELENGTH];
static final private char[]
lookUpBase64Alphabet = new char[LOOKUPLENGTH];
for (int i = 0; i & BASELENGTH; ++i) {
base64Alphabet[i] = -1;
for (int i = 'Z'; i &= 'A'; i--) {
base64Alphabet[i] = (byte) (i - 'A');
for (int i = 'z'; i &= 'a'; i--) {
base64Alphabet[i] = (byte) (i - 'a' + 26);
for (int i = '9'; i &= '0'; i--) {
base64Alphabet[i] = (byte) (i - '0' + 52);
base64Alphabet['+'] = 62;
base64Alphabet['/'] = 63;
for (int i = 0; i &= 25; i++) {
lookUpBase64Alphabet[i] = (char) ('A' + i);
for (int i = 26, j = 0; i &= 51; i++, j++) {
lookUpBase64Alphabet[i] = (char) ('a' + j);
for (int i = 52, j = 0; i &= 61; i++, j++) {
lookUpBase64Alphabet[i] = (char) ('0' + j);
lookUpBase64Alphabet[62] = (char) '+';
lookUpBase64Alphabet[63] = (char) '/';
private static boolean isWhiteSpace(char octect) {
return (octect == 0x20 || octect == 0xd || octect == 0xa || octect == 0x9);
private static boolean isPad(char octect) {
return (octect == PAD);
private static boolean isData(char octect) {
return (octect & BASELENGTH && base64Alphabet[octect] != -1);
* Encodes hex octects into Base64
* @param binaryData Array containing binaryData
* @return Encoded Base64 array
public static String encode(byte[] binaryData) {
if (binaryData == null) {
int lengthDataBits = binaryData.length * EIGHTBIT;
if (lengthDataBits == 0) {
return &&;
int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP;
int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP;
int numberQuartet = fewerThan24bits != 0 ? numberTriplets + 1 : numberT
char encodedData[] =
encodedData = new char[numberQuartet * 4];
byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0;
int encodedIndex = 0;
int dataIndex = 0;
if (fDebug) {
System.out.println(&number of triplets = & + numberTriplets);
for (int i = 0; i & numberT i++) {
b1 = binaryData[dataIndex++];
b2 = binaryData[dataIndex++];
b3 = binaryData[dataIndex++];
if (fDebug) {
System.out.println(&b1= & + b1 + &, b2= & + b2 + &, b3= & + b3);
l = (byte) (b2 & 0x0f);
k = (byte) (b1 & 0x03);
byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 && 2) : (byte) ((b1) && 2 ^ 0xc0);
byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 && 4) : (byte) ((b2) && 4 ^ 0xf0);
byte val3 = ((b3 & SIGN) == 0) ? (byte) (b3 && 6) : (byte) ((b3) && 6 ^ 0xfc);
if (fDebug) {
System.out.println(&val2 = & + val2);
System.out.println(&k4
= & + (k && 4));
System.out.println(&vak
= & + (val2 | (k && 4)));
encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k && 4)];
encodedData[encodedIndex++] = lookUpBase64Alphabet[(l && 2) | val3];
encodedData[encodedIndex++] = lookUpBase64Alphabet[b3 & 0x3f];
// form integral number of 6-bit groups
if (fewerThan24bits == EIGHTBIT) {
b1 = binaryData[dataIndex];
k = (byte) (b1 & 0x03);
if (fDebug) {
System.out.println(&b1=& + b1);
System.out.println(&b1&&2 = & + (b1 && 2));
byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 && 2) : (byte) ((b1) && 2 ^ 0xc0);
encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
encodedData[encodedIndex++] = lookUpBase64Alphabet[k && 4];
encodedData[encodedIndex++] = PAD;
encodedData[encodedIndex++] = PAD;
} else if (fewerThan24bits == SIXTEENBIT) {
b1 = binaryData[dataIndex];
b2 = binaryData[dataIndex + 1];
l = (byte) (b2 & 0x0f);
k = (byte) (b1 & 0x03);
byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 && 2) : (byte) ((b1) && 2 ^ 0xc0);
byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 && 4) : (byte) ((b2) && 4 ^ 0xf0);
encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k && 4)];
encodedData[encodedIndex++] = lookUpBase64Alphabet[l && 2];
encodedData[encodedIndex++] = PAD;
return new String(encodedData);
* Decodes Base64 data into octects
* @param encoded string containing Base64 data
* @return Array containind decoded data.
public static byte[] decode(String encoded) {
if (encoded == null) {
char[] base64Data = encoded.toCharArray();
// remove white spaces
int len = removeWhiteSpace(base64Data);
if (len % FOURBYTE != 0) {
//should be divisible by four
int numberQuadruple = (len / FOURBYTE);
if (numberQuadruple == 0) {
return new byte[0];
byte decodedData[] =
byte b1 = 0, b2 = 0, b3 = 0, b4 = 0;
char d1 = 0, d2 = 0, d3 = 0, d4 = 0;
int i = 0;
int encodedIndex = 0;
int dataIndex = 0;
decodedData = new byte[(numberQuadruple) * 3];
for (; i & numberQuadruple - 1; i++) {
if (!isData((d1 = base64Data[dataIndex++])) || !isData((d2 = base64Data[dataIndex++]))
|| !isData((d3 = base64Data[dataIndex++]))
|| !isData((d4 = base64Data[dataIndex++]))) {
}//if found &no data& just return null
b1 = base64Alphabet[d1];
b2 = base64Alphabet[d2];
b3 = base64Alphabet[d3];
b4 = base64Alphabet[d4];
decodedData[encodedIndex++] = (byte) (b1 && 2 | b2 && 4);
decodedData[encodedIndex++] = (byte) (((b2 & 0xf) && 4) | ((b3 && 2) & 0xf));
decodedData[encodedIndex++] = (byte) (b3 && 6 | b4);
if (!isData((d1 = base64Data[dataIndex++])) || !isData((d2 = base64Data[dataIndex++]))) {
//if found &no data& just return null
b1 = base64Alphabet[d1];
b2 = base64Alphabet[d2];
d3 = base64Data[dataIndex++];
d4 = base64Data[dataIndex++];
if (!isData((d3)) || !isData((d4))) {//Check if they are PAD characters
if (isPad(d3) && isPad(d4)) {
if ((b2 & 0xf) != 0)//last 4 bits should be zero
byte[] tmp = new byte[i * 3 + 1];
System.arraycopy(decodedData, 0, tmp, 0, i * 3);
tmp[encodedIndex] = (byte) (b1 && 2 | b2 && 4);
} else if (!isPad(d3) && isPad(d4)) {
b3 = base64Alphabet[d3];
if ((b3 & 0x3) != 0)//last 2 bits should be zero
byte[] tmp = new byte[i * 3 + 2];
System.arraycopy(decodedData, 0, tmp, 0, i * 3);
tmp[encodedIndex++] = (byte) (b1 && 2 | b2 && 4);
tmp[encodedIndex] = (byte) (((b2 & 0xf) && 4) | ((b3 && 2) & 0xf));
} else { //No PAD e.g 3cQl
b3 = base64Alphabet[d3];
b4 = base64Alphabet[d4];
decodedData[encodedIndex++] = (byte) (b1 && 2 | b2 && 4);
decodedData[encodedIndex++] = (byte) (((b2 & 0xf) && 4) | ((b3 && 2) & 0xf));
decodedData[encodedIndex++] = (byte) (b3 && 6 | b4);
return decodedD
* remove WhiteSpace from MIME containing encoded Base64 data.
* @param data
the byte array of base64 data (with WS)
the new length
private static int removeWhiteSpace(char[] data) {
if (data == null) {
// count characters that's not whitespace
int newSize = 0;
int len = data.
for (int i = 0; i & i++) {
if (!isWhiteSpace(data[i])) {
data[newSize++] = data[i];
return newS
最后是一个MainTest:package com.
public class MainTest {
public static void main(String[] args) throws Exception {
String filepath=&G:/tmp/&;
//RSAEncrypt.genKeyPair(filepath);
System.out.println(&--------------公钥加密私钥解密过程-------------------&);
String plainText=&ihep_公钥加密私钥解密&;
//公钥加密过程
byte[] cipherData=RSAEncrypt.encrypt(RSAEncrypt.loadPublicKeyByStr(RSAEncrypt.loadPublicKeyByFile(filepath)),plainText.getBytes());
String cipher=Base64.encode(cipherData);
//私钥解密过程
byte[] res=RSAEncrypt.decrypt(RSAEncrypt.loadPrivateKeyByStr(RSAEncrypt.loadPrivateKeyByFile(filepath)), Base64.decode(cipher));
String restr=new String(res);
System.out.println(&原文:&+plainText);
System.out.println(&加密:&+cipher);
System.out.println(&解密:&+restr);
System.out.println();
System.out.println(&--------------私钥加密公钥解密过程-------------------&);
plainText=&ihep_私钥加密公钥解密&;
//私钥加密过程
cipherData=RSAEncrypt.encrypt(RSAEncrypt.loadPrivateKeyByStr(RSAEncrypt.loadPrivateKeyByFile(filepath)),plainText.getBytes());
cipher=Base64.encode(cipherData);
//公钥解密过程
res=RSAEncrypt.decrypt(RSAEncrypt.loadPublicKeyByStr(RSAEncrypt.loadPublicKeyByFile(filepath)), Base64.decode(cipher));
restr=new String(res);
System.out.println(&原文:&+plainText);
System.out.println(&加密:&+cipher);
System.out.println(&解密:&+restr);
System.out.println();
System.out.println(&---------------私钥签名过程------------------&);
String content=&ihep_这是用于签名的原始数据&;
String signstr=RSASignature.sign(content,RSAEncrypt.loadPrivateKeyByFile(filepath));
System.out.println(&签名原串:&+content);
System.out.println(&签名串:&+signstr);
System.out.println();
System.out.println(&---------------公钥校验签名------------------&);
System.out.println(&签名原串:&+content);
System.out.println(&签名串:&+signstr);
System.out.println(&验签结果:&+RSASignature.doCheck(content, signstr, RSAEncrypt.loadPublicKeyByFile(filepath)));
System.out.println();
看看运行截图:转载请注明:
&&相关文章推荐
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:1396441次
积分:12117
积分:12117
排名:第1180名
原创:126篇
评论:651条
NAME:FCPlayer
CITY:Beijing
Degree:Master
Skills:Java、IOS、.NET
文章:11篇
阅读:131966
(1)(1)(1)(1)(1)(2)(2)(1)(1)(1)(2)(1)(1)(1)(1)(1)(3)(5)(6)(1)(5)(5)(5)(4)(2)(8)(5)(5)(8)(14)(16)(5)(5)(5)(3)(2)(1)(2)(3)

我要回帖

更多关于 java公钥加密私钥解密 的文章

 

随机推荐