RSA加密演算法是一种非对称加密演算法,可靠性比较强,具体请自行谷歌。
最近公司需要一个能生成RSA密钥进行加解密的客户端,并要将生成的密钥提供给JAVA服务端进行数据交互,谷歌后发现网上并没有可用的,DELPHI的lockbox控件可能加解密与编码方式和JAVA不同,所以生成的密钥和加解密文都无法进行交互。
客户端使用DELPHI实现,在这要感谢http://www.cnblogs.com/midea0978/archive/2007/06/02/768821.html
博主的RSA加解密签名验证DLL。
RSA主要是生成两个足够大的随机素数,进行一些算法生成3个参数modulus、publicExponent、privateExponet,有了这3个参数就可以使用JAVA来生成RSA公私钥,进行加解密和签名,这段JAVA代码应该是1024位的RSA加解密,DELPHI客户端经过我与JAVA生成的参数进行比对修改后,可以直接使用。
DELPHI客户端使用先点击生成随机数,然后点击生成密钥,然后就可以输入明文或者密文进行加解密了,DLL也带签名功能,如有需要请自行添加。
由于字符加解密处理大量字符时会严重影响效率,近期正在尝试DELPHI-JAVA RSA对文件的加解密,如果尝试成功,再和大家分享。
Java 代码
package cn.commom.cipher.rsa;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.math.BigInteger;
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.SecureRandom;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
import javax.crypto.Cipher;
import cn.commom.cipher.Base64.Base64;
/**
* RSA 工具类。提供加密,解密,生成密钥对等方法。
* 需要到http://www.bouncycastle.org下载bcprov-jdk14-123.jar。
*
*/
public class RSAUtil {
/**
* * 生成密钥对 *
*
* @return KeyPair *
* @throws EncryptException
*/
public static KeyPair generateKeyPair() throws Exception {
try {
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA",
new org.bouncycastle.jce.provider.BouncyCastleProvider());
final int KEY_SIZE = 1024;// 没什么好说的了,这个值关系到块加密的大小,可以更改,但是不要太大,否则效率会低
keyPairGen.initialize(KEY_SIZE, new SecureRandom());
KeyPair keyPair = keyPairGen.generateKeyPair();
// saveKeyPair(keyPair);
return keyPair;
} catch (Exception e) {
throw new Exception(e.getMessage());
}
}
public static KeyPair getKeyPair()throws Exception{
FileInputStream fis = new FileInputStream("C:/RSAKey.txt");
ObjectInputStream oos = new ObjectInputStream(fis);
KeyPair kp= (KeyPair) oos.readObject();
oos.close();
fis.close();
return kp;
}
public static void saveKeyPair(KeyPair kp)throws Exception{
FileOutputStream fos = new FileOutputStream("C:/RSAKey.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
//生成密钥
oos.writeObject(kp);
oos.close();
fos.close();
}
/**
* * 生成公钥 *
*
* @param modulus *
* @param publicExponent *
* @return RSAPublicKey *
* @throws Exception
*/
public static RSAPublicKey generateRSAPublicKey(String modulus,
String publicExponent) throws Exception {
KeyFactory keyFac = null;
try {
keyFac = KeyFactory.getInstance("RSA",
new org.bouncycastle.jce.provider.BouncyCastleProvider());
} catch (NoSuchAlgorithmException ex) {
throw new Exception(ex.getMessage());
}
RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger(
modulus), new BigInteger(publicExponent));
try {
return (RSAPublicKey) keyFac.generatePublic(pubKeySpec);
} catch (InvalidKeySpecException ex) {
throw new Exception(ex.getMessage());
}
}
/**
* * 生成私钥 *
*
* @param modulus *
* @param privateExponent *
* @return RSAPrivateKey *
* @throws Exception
*/
public static RSAPrivateKey generateRSAPrivateKey(String modulus,
String privateExponent) throws Exception {
KeyFactory keyFac = null;
try {
keyFac = KeyFactory.getInstance("RSA",
new org.bouncycastle.jce.provider.BouncyCastleProvider());
} catch (NoSuchAlgorithmException ex) {
throw new Exception(ex.getMessage());
}
RSAPrivateKeySpec priKeySpec = new RSAPrivateKeySpec(new BigInteger(
modulus), new BigInteger(privateExponent));
try {
return (RSAPrivateKey) keyFac.generatePrivate(priKeySpec);
} catch (InvalidKeySpecException ex) {
throw new Exception(ex.getMessage());
}
}
/**
* * 加密 *
*
* @param key
* 加密的密钥 *
* @param data
* 待加密的明文数据 *
* @return 加密后的数据 *
* @throws Exception
*/
public static byte[] encrypt(PublicKey pk, byte[] data) throws Exception {
try {
Cipher cipher = Cipher.getInstance("RSA",
new org.bouncycastle.jce.provider.BouncyCastleProvider());
cipher.init(Cipher.ENCRYPT_MODE, pk);
int blockSize = cipher.getBlockSize();// 获得加密块大小,如:加密前数据为128个byte,而key_size=1024
// 加密块大小为127
// byte,加密后为128个byte;因此共有2个加密块,第一个127
// byte第二个为1个byte
int outputSize = cipher.getOutputSize(data.length);// 获得加密块加密后块大小
int leavedSize = data.length % blockSize;
int blocksSize = leavedSize != 0 ? data.length / blockSize + 1
: data.length / blockSize;
byte[] raw = new byte[outputSize * blocksSize];
int i = 0;
while (data.length - i * blockSize > 0) {
if (data.length - i * blockSize > blockSize)
cipher.doFinal(data, i * blockSize, blockSize, raw, i
* outputSize);
else
cipher.doFinal(data, i * blockSize, data.length - i
* blockSize, raw, i * outputSize);
// 这里面doUpdate方法不可用,查看源代码后发现每次doUpdate后并没有什么实际动作除了把byte[]放到
// ByteArrayOutputStream中,而最后doFinal的时候才将所有的byte[]进行加密,可是到了此时加密块大小很可能已经超出了
// OutputSize所以只好用dofinal方法。
i++;
}
return raw;
} catch (Exception e) {
throw new Exception(e.getMessage());
}
}
/**
* * 解密 *
*
* @param key
* 解密的密钥 *
* @param raw
* 已经加密的数据 *
* @return 解密后的明文 *
* @throws Exception
*/
public static byte[] decrypt(PrivateKey pk, byte[] raw) throws Exception {
try {
Cipher cipher = Cipher.getInstance("RSA",
new org.bouncycastle.jce.provider.BouncyCastleProvider());
cipher.init(cipher.DECRYPT_MODE, pk);
int blockSize = cipher.getBlockSize();
ByteArrayOutputStream bout = new ByteArrayOutputStream(64);
int j = 0;
while (raw.length - j * blockSize > 0) {
bout.write(cipher.doFinal(raw, j * blockSize, blockSize));
j++;
}
return bout.toByteArray();
} catch (Exception e) {
throw new Exception(e.getMessage());
}
}
/**
* * *
*
* @param args *
* @throws Exception
*/
public static void main(String[] args) throws Exception {
BigInteger m = new BigInteger("114910746036410253316314040228614738318764669036434024095717804758778255980644061211555252688148063860512113620483170750011694185664755320636550380918375847427113050482880850397431166396031396178697561589829929631830943951420731244238401558090688756762945564806804559911355363795386021049659288978979933771007");
BigInteger pue = new BigInteger("65537");
BigInteger pre = new BigInteger("46371431411644444656553663150986068698847509071311940358262489623501358559593717851930997265902064865570448695208788257438762869900615668905416489743684023945568860452420766662065548276937318670516711330254079808768146331439707761102137016010658521613583135350799554187576765145604206921126394502908531195233");
String modulus = String.valueOf(m);
String publicExponent = String.valueOf(pue);
String privateExponet = String.valueOf(pre);
RSAPublicKey pk = RSAUtil.generateRSAPublicKey(modulus,publicExponent);
RSAPrivateKey pik = RSAUtil.generateRSAPrivateKey(modulus,privateExponet);
String test = "hello加密";
String en_test = RSATool.encryptByRSA(Base64.encode(pk.getEncoded()), test);
System.out.println("加密: "+en_test);
String de_test = RSATool.decryptByRSA(Base64.encode(pik.getEncoded()), "E7w8zW920oN4Hdssqa8zLtq6tX2MuIiRbfK37X4T53UzOXXLwj95Th40OBt5Ov/1m43fq6kNgWmLKrAXnFhDIbOdkgtQ5ynKVBVjbz2abbkEXUdASl9S4PPrj9vnhGId2W3Nlju4H26z83+SiDMt4l7PbkmxAhAz//bUPVo+IpM=");
System.out.println("解密:"+de_test);
}
}