这里的base64的依赖不一样,一个是apache,一个是sun的  ,由于base64的依赖不同,导致在IOS中解析不了!

package com.handsight.platform.cipher;

import java.io.ByteArrayOutputStream;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map; import javax.crypto.Cipher; import sun.misc.BASE64Decoder; //据说是sun公司未发布jar
import sun.misc.BASE64Encoder; public class CreateSecretKey { public static final String KEY_ALGORITHM = "RSA";
private static final String PUBLIC_KEY = "RSAPublicKey";
private static final String PRIVATE_KEY = "RSAPrivateKey";
public static final String SIGNATURE_ALGORITHM = "MD5withRSA";
/**
* * RSA最大加密明文大小
*/ private static final int MAX_ENCRYPT_BLOCK = 117;
/**
* * RSA最大解密密文大小
*/ private static final int MAX_DECRYPT_BLOCK = 128; // 获得公钥字符串 public static String getPublicKeyStr(Map<String, Object> keyMap) throws Exception {
// 获得map中的公钥对象 转为key对象
Key key = (Key) keyMap.get(PUBLIC_KEY);
// 编码返回字符串
return encryptBASE64(key.getEncoded());
} // 获得私钥字符串 public static String getPrivateKeyStr(Map<String, Object> keyMap) throws Exception {
// 获得map中的私钥对象 转为key对象
Key key = (Key) keyMap.get(PRIVATE_KEY);
// 编码返回字符串
return encryptBASE64(key.getEncoded());
} // 获取公钥 public static PublicKey getPublicKey(String key) throws Exception {
byte[] keyBytes;
keyBytes = (new BASE64Decoder()).decodeBuffer(key);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
PublicKey publicKey = keyFactory.generatePublic(keySpec);
return publicKey;
} // 获取私钥 public static PrivateKey getPrivateKey(String key) throws Exception {
byte[] keyBytes;
keyBytes = (new BASE64Decoder()).decodeBuffer(key);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
return privateKey;
} // 解码返回byte public static byte[] decryptBASE64(String key) throws Exception {
return (new BASE64Decoder()).decodeBuffer(key);
} // 编码返回字符串 public static String encryptBASE64(byte[] key) throws Exception {
return (new BASE64Encoder()).encodeBuffer(key);
} // ***************************签名和验证******************************* public static byte[] sign(byte[] data, String privateKeyStr) throws Exception {
PrivateKey priK = getPrivateKey(privateKeyStr);
Signature sig = Signature.getInstance(SIGNATURE_ALGORITHM);
sig.initSign(priK);
sig.update(data);
return sig.sign();
} public static boolean verify(byte[] data, byte[] sign, String publicKeyStr) throws Exception {
PublicKey pubK = getPublicKey(publicKeyStr);
Signature sig = Signature.getInstance(SIGNATURE_ALGORITHM);
sig.initVerify(pubK);
sig.update(data);
return sig.verify(sign);
} // ************************加密解密************************** public static byte[] encrypt(byte[] plainText, String publicKeyStr) throws Exception {
PublicKey publicKey = getPublicKey(publicKeyStr);
Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
int inputLen = plainText.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
int i = 0;
byte[] cache;
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
cache = cipher.doFinal(plainText, offSet, MAX_ENCRYPT_BLOCK);
} else {
cache = cipher.doFinal(plainText, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_ENCRYPT_BLOCK;
}
byte[] encryptText = out.toByteArray();
out.close();
return encryptText;
} public static byte[] decrypt(byte[] encryptText, String privateKeyStr) throws Exception {
PrivateKey privateKey = getPrivateKey(privateKeyStr);
Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
int inputLen = encryptText.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 对数据分段解密
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
cache = cipher.doFinal(encryptText, offSet, MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(encryptText, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_DECRYPT_BLOCK;
}
byte[] plainText = out.toByteArray();
out.close();
return plainText;
} public static void main(String[] args) {
Map<String, Object> keyMap;
byte[] cipherText;
String input = "Hello World!";
try {
keyMap = initKey();
String publicKey = getPublicKeyStr(keyMap);
System.out.println("公钥------------------");
System.out.println(publicKey);
String privateKey = getPrivateKeyStr(keyMap);
System.out.println("私钥------------------");
System.out.println(privateKey); System.out.println("测试可行性-------------------");
System.out.println("明文=======" + input); cipherText = encrypt(input.getBytes(), publicKey);
// 加密后的东西 
System.out.println("密文=======" + new String(cipherText));
// 开始解密 
byte[] plainText = decrypt(cipherText, privateKey);
System.out.println("解密后明文===== " + new String(plainText));
System.out.println("验证签名-----------");
String str = "被签名的内容";
System.out.println("\n原文:" + str);
byte[] signature = sign(str.getBytes(), privateKey);
boolean status = verify(str.getBytes(), signature, publicKey);
System.out.println("验证情况:" + status);
} catch (Exception e) {
e.printStackTrace();
}
} public static Map<String, Object> initKey() throws Exception {
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
keyPairGen.initialize(1024);
KeyPair keyPair = keyPairGen.generateKeyPair();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
Map<String, Object> keyMap = new HashMap<String, Object>(2);
keyMap.put(PUBLIC_KEY, publicKey);
keyMap.put(PRIVATE_KEY, privateKey);
return keyMap;
}
}

测试:

package com.handsight.platform.cipher;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.math.BigInteger;
import java.security.GeneralSecurityException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec; import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey; import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter; public class TestRSA {
// RSA算法对文件加密
public void encryptByRSA(String fileName, String saveFileName, String keyFileName) throws Exception {
long start = System.currentTimeMillis();
try {
KeyGenerator keygen = KeyGenerator.getInstance("AES");
SecureRandom random = new SecureRandom();
keygen.init(random);
SecretKey key = keygen.generateKey();
String[] result = readKeyUtil(new File(keyFileName));
RSAPublicKey key2 = getPublicKey(result[0], result[1]);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.WRAP_MODE, key2);
byte[] wrappedKey = cipher.wrap(key);
DataOutputStream out = new DataOutputStream(new FileOutputStream(saveFileName));
out.writeInt(wrappedKey.length);
out.write(wrappedKey);
InputStream in = new FileInputStream(fileName);
cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, key);
crypt(in, out, cipher);
in.close();
out.close();
} catch (GeneralSecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
long end = System.currentTimeMillis();
System.out.println("总共耗时:" + (end - start));
} // RSA算法对文件解密
public void decryptByRSA(String fileName, String saveFileName, String keyFileName) throws Exception {
try {
DataInputStream in = new DataInputStream(new FileInputStream(fileName));
int length = in.readInt();
byte[] wrappedKey = new byte[length];
in.read(wrappedKey, 0, length);
String[] result = readKeyUtil(new File(keyFileName));
RSAPrivateKey key2 = getPrivateKey(result[0], result[1]); Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.UNWRAP_MODE, key2);
Key key = cipher.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY); OutputStream out = new FileOutputStream(saveFileName);
cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, key); crypt(in, out, cipher);
in.close();
out.close();
} catch (GeneralSecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} //对数据块加密
public void crypt(InputStream in, OutputStream out, Cipher cipher) throws IOException, GeneralSecurityException {
int blockSize = cipher.getBlockSize();
int outputSize = cipher.getOutputSize(blockSize);
byte[] inBytes = new byte[blockSize];
byte[] outBytes = new byte[outputSize]; int inLength = 0;
boolean next = true;
while (next) {
inLength = in.read(inBytes);
System.out.println(inLength);
if (inLength == blockSize) {
int outLength = cipher.update(inBytes, 0, blockSize, outBytes);
out.write(outBytes, 0, outLength);
} else {
next = false;
}
}
if (inLength > 0) {
outBytes = cipher.doFinal(inBytes, 0, inLength);
} else {
outBytes = cipher.doFinal();
}
out.write(outBytes);
} //生成RSA密钥对
public void generateRSAKey(String savePath) throws Exception {
try {
KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA");
SecureRandom random = new SecureRandom();
keygen.initialize(RSA_KEYSIZE, random);
KeyPair keyPair = keygen.generateKeyPair();
RSAPublicKey puk = (RSAPublicKey) keyPair.getPublic();
createXmlFile(puk.getModulus().toString(), puk.getPublicExponent().toString(), savePath + "\\public.xml");
RSAPrivateKey prk = (RSAPrivateKey) keyPair.getPrivate();
createXmlFile(prk.getModulus().toString(), prk.getPrivateExponent().toString(), savePath + "\\private.xml");
/*
* OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(savePath
* + "\\public.xml")); // 得到公钥字符串 System.out.println(puk.getModulus());
* System.out.println(puk.getPublicExponent());
* System.out.println(prk.getModulus());
* System.out.println(prk.getPrivateExponent()); // 得到私钥字符串
* osw.write(createXmlFile(puk.getModulus().toString(),
* puk.getPublicExponent().toString())); osw.close(); osw = new
* OutputStreamWriter(new FileOutputStream(savePath + "\\private.xml"));
* osw.write(createXmlFile(prk.getModulus().toString(),
* prk.getPrivateExponent().toString())); osw.close();
*/
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
} /**
* 使用模和指数生成RSA公钥
* 注意:【此代码用了默认补位方式,为RSA/None/PKCS1Padding,不同JDK默认的补位方式可能不同,如Android默认是RSA
* /None/NoPadding】
*
* @param modulus 模
* @param exponent 指数
* @return
*/
public static RSAPublicKey getPublicKey(String modulus, String exponent) {
try {
BigInteger b1 = new BigInteger(modulus);
BigInteger b2 = new BigInteger(exponent);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(b1, b2);
return (RSAPublicKey) keyFactory.generatePublic(keySpec);
} catch (Exception e) {
e.printStackTrace();
return null;
}
} /**
* 使用模和指数生成RSA私钥
* 注意:【此代码用了默认补位方式,为RSA/None/PKCS1Padding,不同JDK默认的补位方式可能不同,如Android默认是RSA
* /None/NoPadding】
*
* @param modulus 模
* @param exponent 指数
* @return
*/
public static RSAPrivateKey getPrivateKey(String modulus, String exponent) {
try {
BigInteger b1 = new BigInteger(modulus);
BigInteger b2 = new BigInteger(exponent);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(b1, b2);
return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
} catch (Exception e) {
e.printStackTrace();
return null;
}
} /**
* 生成xml字符串
*
* @return
* @throws Exception
*/
public static void createXmlFile(String Modulus, String Exponent, String filepath) throws Exception {
Document document = DocumentHelper.createDocument();
Element root = document.addElement("root");
Element supercarElement = root.addElement("Modulus"); supercarElement.addText(Modulus);
Element supercarElement2 = root.addElement("Exponent"); supercarElement2.addText(Exponent);
// 写入到一个新的文件中
writer(document, filepath);
} /**
* 把document对象写入新的文件
*
* @param document
* @throws Exception
*/
public static void writer(Document document, String path) throws Exception {
// 紧凑的格式
// 排版缩进的格式
OutputFormat format = OutputFormat.createPrettyPrint();
// 设置编码
format.setEncoding("UTF-8");
// 创建XMLWriter对象,指定了写出文件及编码格式
XMLWriter writer = new XMLWriter(new OutputStreamWriter(new FileOutputStream(new File(path)), "UTF-8"), format);
// 写入
writer.write(document);
// 立即写入
writer.flush();
// 关闭操作
writer.close();
} public String[] readKeyUtil(File file) throws DocumentException {
// 创建saxReader对象
SAXReader reader = new SAXReader();
// 通过read方法读取一个文件 转换成Document对象
Document document = reader.read(file);
// 获取根节点元素对象
Element node = document.getRootElement();
Element ele = node.element("Modulus");
String Modulus = ele.getTextTrim();
Element ele1 = node.element("Exponent");
String Exponent = ele1.getTextTrim();
return new String[] { Modulus, Exponent };
} private static final int RSA_KEYSIZE = 1024; public static void main(String[] args) throws Exception {
String path ="E:/home/handsight/aic/";
// 生成xml格式的公钥和私钥
new TestRSA().generateRSAKey(path);
// 对文件进行加密
new TestRSA().encryptByRSA(path + "/12345.txt", path + "/456.txt", path + "/public.xml");
// 对文件进行解密
new TestRSA().decryptByRSA(path + "/456.txt", path + "/12345_new.txt", path + "/private.xml");
}
}

RSA加密的java实现2(交互IOS)的更多相关文章

  1. php RSA 加密 与java加密互交,java解密

    <? php class encrypt{ var $pub_key; function redPukey() { $pubKey = "MIIDhzCCAm+gAwIBAgIGASY ...

  2. RSA加密的java实现

    首先科普一波: RSA的1024位是指公钥及私钥分别是1024bit,也就是1024/8=128 Bytes RSA算法密钥长度的选择是安全性和程序性能平衡的结果,密钥长度越长,安全性越好,加密解密所 ...

  3. JS客户端RSA加密,Java服务端解密

    常用语网页客户端对密码加密,在后端java解密还原 java代码依赖    <dependency>      <groupId>commons-codec</group ...

  4. 通用RSA加密 - PHP+Java+Javascript加密解密

    php端生成 公钥私钥 1.openssl genrsa -out rsa_private_key.pem 1024    私钥 2.openssl rsa -in rsa_private_key.p ...

  5. c# RSA 加密解密 java.net公钥私钥转换 要解密的模块大于128字节

    有一个和接口对接的任务,对方使用的是java,我方使用的是c#,接口加密类型为RSA,公钥加密私钥解密. 然后就是解决各种问题. 1.转换对方的密钥字符串 由于c#里面需要使用的是xml各式的密钥字符 ...

  6. RSA加密方法java工具类

    package com.qianmi.weidian.common.util; import java.io.ByteArrayOutputStream; import java.security.K ...

  7. encryptjs 加密 前端数据(vue 使用 RSA加密、java 后端 RSA解密)

    1.index.html引入 <script src="./static/js/jsencrypt.min.js"></script> 或者 npm i j ...

  8. RSA加密解密及数字签名Java实现--转

    RSA公钥加密算法是1977年由罗纳德·李维斯特(Ron Rivest).阿迪·萨莫尔(Adi Shamir)和伦纳德·阿德曼(Leonard Adleman)一起提出的.当时他们三人都在麻省理工学院 ...

  9. (转)RSA加密解密及数字签名Java实现

    转:http://my.oschina.net/jiangli0502/blog/171263?fromerr=hc4izFe2  RSA公钥加密算法是1977年由罗纳德·李维斯特(Ron Rives ...

随机推荐

  1. Linux下移动图像监测系统——motion的移植及应用

    移动图像监控主系统的开发 移动图像监控的原理方法: 通过获取摄像头图像,比较前后每一帧的图像数据,从而实现移动物体监控.所有移动监控均是如此,只是图像帧的比较算法不同. 移动图像监控系统的实现 选择开 ...

  2. .net持续集成cake篇之使用vs或者vscode来辅助开发cake脚本

    使用Visual Studio来开发工具 前面我们都是通过手写或者复制的方法来编写Cake文件,Cake使用的是C#语言,如果仅使用简单的文本编辑器来编写显然效率是非常低下的,本节我们讲解如何使用ca ...

  3. Excel催化剂开源第32波-VSTO开发的插件让WPS顺利调用的方法-注册表增加注册信息

    VSTO插件开发完成后,鉴于现在WPS用户也不少,很多时候用户没办法用OFFICE软件,只能在WPS环境下办公,VSTO开发的插件,只需增加一句注册表信息,即可让WPS识别到并调用VSTO开发的功能, ...

  4. [剑指offer] 3. 从头到尾打印链表

    题目描述 输入一个链表,按链表值从尾到头的顺序返回一个ArrayList. 思路: 利用容器,遍历一遍加入到一个新容器里,然后反置输出. vector 用 reverse stack 则直接一个个出栈 ...

  5. 手把手带你入门 Spring Security!

    Spring Security 是 Spring 家族中的一个安全管理框架,实际上,在 Spring Boot 出现之前,Spring Security 就已经发展了多年了,但是使用的并不多,安全管理 ...

  6. AQS初体验

    AQS初体验 AQS是AbstractQueuedSynchronizer的简称.AQS提供了一种实现阻塞锁和一系列依赖FIFO等待队列的同步器的框架.所谓框架,AQS使用了模板方法的设计模式,为我们 ...

  7. PHP对接口执行效率慢的优化

    PHP对接口执行效率慢的优化 PHP对接口执行效率慢的优化 造成执行效率低的原因可以由很多方面找原因 从代码层面,代码质量低,执行效率也会有很大影响的. 从硬件方面,服务器配置低,服务器配置是基础,这 ...

  8. 解读equals()和hashCode()

    前面部分摘自:https://blog.csdn.net/javazejian/article/details/51348320 一:Object中equals方法的实现原理 public boole ...

  9. css关于flex布局下不能实现text-overflow: ellipsis的解决办法

    摘录自 https://segmentfault.com/q/1010000011115918

  10. JNDI资源(一)

    JNDI:Java命名与目录接口 是一个应用程序设计的API,为开发人员提供了查找和访问各种命名和目录的通用.统一的服务. 使用JNDA的步骤: 1.配置资源. //Tomcat跟目录/conf/co ...