Blackberry 6,7 java环境下RSA加密 解密

经过一年的黑莓开发,总结一些东西,记录遇到过的一些问题。  

这里主要记录跟RSA加密解密有关的问题:黑莓端与java服务器端相互加密 解密

1,首先是填充模式使用 java端RSA/ECB/PKCS1Padding与黑莓端PKCS1FormatterEngine对应,刚开始的时候试过其他的几种 不是java端不支持 就是黑莓端不支持,最后确认两边都支持PKCS1Padding模式。

2,黑莓端的公钥和Modules 与 java端的不同:公钥前面加一个0,Modules前面加两个00,(Modules是我在java服务器端生成的)

String publicKeyExponent="010001";
StringpublicKeyModules="0098565b6f053c21f78c645c64aec952989876279a357efe30ab3c75d482c7ef1c16927b2d5a255a
d8beb7059792929885b2054ae005ba4fcaa70da5737e16305d7ecc852802e0360b4ab3c0ba92991a4e41ab49b4403cd46f038c85
9accba8e9229d6dbd8a1ce606b4681d8aea433073bea86ed6514e8600c30e32d94720ddafd";

3,在黑莓端加密以后需要到java端解密  所以需要将加密后的数据转后16进制,至于为什么要转换成16进制 感觉是因为RSA的加密机制吧(不太确定)

4,java端的代码是从网上找来的,大致做了一些修改:

   a,下面new org.bouncycastle.jce.provider.BouncyCastleProvider()的部分没有的话 int blockSize = cipher.getBlockSize(); 这段代码获取模块大小值就会为0.

Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding",
	new org.bouncycastle.jce.provider.BouncyCastleProvider());

 b,RSA加密使用了填充 但是在某种情况下可能会在密文多出一位,用以下代码解决:(我做WinPhone8的同事也遇到了同样的问题 下面带面也可以解决)

		if(raw[0]==0 && raw.length==129)//判断数组首元素是否为0,若是,则将其删除,保证模的位数是128  
	         {  
	              byte[] temp=new byte[raw.length-1];  
	              for(int i=0;i<raw.length-1;i++)  
	              {  
	                   temp[i]=raw[i+1];  
	              } 
	              raw=temp;
	         }  

5,在windows服务器与在linux获取秘钥的路径不同参考:

 public static String getRSAPairFilePath() {
         String urlPath = RSAUtils.class.getResource("/").getPath();
         String path=(new File(urlPath).getParent() +File.separator+ RSAKeyStore);
         return path;
     }


下面上传代码:

BB6,7端:

import java.io.ByteArrayOutputStream;

import net.rim.device.api.crypto.BlockEncryptor;
import net.rim.device.api.crypto.PKCS1FormatterEngine;
import net.rim.device.api.crypto.RSACryptoSystem;
import net.rim.device.api.crypto.RSAEncryptorEngine;
import net.rim.device.api.crypto.RSAPublicKey;


public class RSACryptUtil {
	
	public static String rsaEncrypt(String content) {
		String publicKeyExponent="010001";//公钥
		//Modules
		String publicKeyModules="0098565b6f053c21f78c645c64aec952989876279a357efe30ab3c75d482c7ef1c16927b2d5a255ad8beb7059792929885b2054ae005ba4fcaa70da5737e16305d7ecc852802e0360b4ab3c0ba92991a4e41ab49b4403cd46f038c859accba8e9229d6dbd8a1ce606b4681d8aea433073bea86ed6514e8600c30e32d94720ddafd";
		RSACryptoSystem cryptoSystem;
		try {
			cryptoSystem = new RSACryptoSystem(1024);// 这个值关系到块加密的大小
			RSAPublicKey publicKey=new RSAPublicKey(cryptoSystem, parseHexStr2Byte(publicKeyExponent),
                        parseHexStr2Byte(publicKeyModules));//将公钥与modules转化为二进制 创建RSAPublicKey对象
			RSAEncryptorEngine rsaEngine=new RSAEncryptorEngine(publicKey);
			
			PKCS1FormatterEngine pkcs1Engine=new PKCS1FormatterEngine(rsaEngine);
			ByteArrayOutputStream out=new ByteArrayOutputStream();
			BlockEncryptor encrypt=new BlockEncryptor(pkcs1Engine, out);
			encrypt.write(content.getBytes());
			encrypt.close();
			out.close();
			byte[] bt=out.toByteArray();
			return parseByte2HexStr(bt);//转换成16进制.
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return null;
	}
	
	 /**将16进制转换为二进制  
     * @param hexStr  
     * @return  
     */  
	public static byte[] parseHexStr2Byte(String hexStr) { 
		byte[] result=new byte[hexStr.length()/2];
		for(int i=0;i<hexStr.length()/2;i++){
			int high=Integer.parseInt(hexStr.substring(i*2, i*2+1),16);
			int low=Integer.parseInt(hexStr.substring(i*2+1, i*2+2),16);
			result[i]=(byte)(high*16+low);
		}
		return result;
	}
	/**将二进制转换成16进制  
     * @param buf  
     * @return  
     */ 
	public static String parseByte2HexStr(byte buf[]) {
		StringBuffer sb=new StringBuffer();
		for(int i=0;i<buf.length;i++){
			String hex=Integer.toHexString(buf[i]&0xFF);
			if(hex.length()==1){
				hex='0'+hex;
			}
			sb.append(hex.toUpperCase());
		}
		return sb.toString();
	}


}


java端:

import java.io.ByteArrayOutputStream;
import java.io.File;
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;

public class RSABBSixUtil {
	private static String RSAKeyStore = "RSAKey.txt";
	/**
	 * * 生成密钥对 *
	 * 
	 * @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();
			RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
			RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
			System.out.println(publicKey.getModulus().toString(16));
			System.out.println(publicKey.getPublicExponent().toString(16));
			System.out.println(privateKey.getPrivateExponent().toString(16));
			System.out.println(publicKey.getPublicExponent().toString(16).length());
			System.out.println(privateKey.getPrivateExponent().toString(16).length());
			System.out.println("99e28e237fa52ee766e38db10b2bbbcc3fc8f0549781547bbef2d75e952d1f5fda9bb0b61964760fdab21c3f4a940a51e80781da50dd9623ac589a152998e1710b549677e40b74d81bbb039eb8196bda28a9e8c53920f5da1c23e559b9afc39d08dfce7f00fdef88059bec49063f57179628aa259e63d2bf837057b0b25cadf3".length());
			
			saveKeyPair(keyPair);
			return keyPair;
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		}
	}
	
	 public static String getRSAPairFilePath() {
         String urlPath = RSAUtils.class.getResource("/").getPath();
         String path=(new File(urlPath).getParent() +File.separator+ RSAKeyStore);
         return path;//(new File(urlPath).getParent() + RSAKeyStore);
     }


	public static KeyPair getKeyPair() throws Exception {
		String path=getRSAPairFilePath();
		System.out.println(path);
		FileInputStream fis = new FileInputStream(path);
		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(RSAKeyStore);
		ObjectOutputStream oos = new ObjectOutputStream(fos);
		// 生成密钥
		oos.writeObject(kp);
		oos.close();
		fos.close();
	}

	/**
	 * * 生成公钥 *
	 * 
	 * @param modulus *
	 * @param publicExponent *
	 * @return RSAPublicKey *
	 * @throws Exception
	 */
	public static RSAPublicKey generateRSAPublicKey(byte[] modulus,
			byte[] 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(byte[] modulus,
			byte[] 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/ECB/PKCS1Padding",
					new org.bouncycastle.jce.provider.BouncyCastleProvider());
			cipher.init(cipher.DECRYPT_MODE, pk);
			int blockSize = cipher.getBlockSize();
			ByteArrayOutputStream bout = new ByteArrayOutputStream(64);
			int j = 0;
			
			if(raw[0]==0 && raw.length==129)//判断数组首元素是否为0,若是,则将其删除,保证模的位数是128  
	         {  
	              byte[] temp=new byte[raw.length-1];  
	              for(int i=0;i<raw.length-1;i++)  
	              {  
	                   temp[i]=raw[i+1];  
	              } 
	              raw=temp;
	         }  
			
			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());
		}
	}
	
	public static String decrypt(String result) throws Exception{
		byte[] en_result = new BigInteger(result, 16).toByteArray();
		try{
			byte[] de_result = decrypt(getKeyPair().getPrivate(),
					en_result);
			StringBuffer sb = new StringBuffer();
			sb.append(new String(de_result));
			String pwd = sb.toString();
			return pwd;
		}catch(Exception e){
			throw new Exception(e.getMessage());
		}
	}
}


java端代码参考:http://sosuny.iteye.com/blog/793327
BB6,7端代码参考:http://stackoverflow.com/questions/5248590/error-while-using-rsa-encryption-on-blackberry

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值