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

来源:互联网 发布:做网络兼职是真的吗 编辑:程序博客网 时间:2024/05/01 08:02
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;
}


}

0 0
原创粉丝点击