您的位置:首页 > 移动开发 > Android开发

android代码16进制公钥进行RSA加密

2017-01-13 15:47 423 查看
import java.math.BigInteger;

import java.security.KeyFactory;

import java.security.PublicKey;

import java.security.interfaces.RSAPublicKey;

import java.security.spec.RSAPublicKeySpec;

import javax.crypto.Cipher;

public final class RSAUtils {

/**
* 获取公钥方法(16进制公钥)
* @param modulus  公钥字符串(128字节)
* @param exponent  公钥指数 "10001"
* @return 公钥
*/

public static RSAPublicKey getPublicKey(String modulus, String exponent) {
try {
BigInteger n = new BigInteger(modulus, 16); // 此处为进制数
BigInteger e = new BigInteger(exponent, 16);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(n, e);
return (RSAPublicKey) keyFactory.generatePublic(keySpec);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}

/**
* 加密

* @param key
*            加密的密钥
* @param data
*            待加密的明文数据
* @return 加密后的数据
* @throws Exception
*/
public static byte[] encrypt(byte[] bt_plaintext, PublicKey key)
throws Exception {

Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] bt_encrypted = cipher.doFinal(bt_plaintext);
return bt_encrypted;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  rsa 加密 android