java rsa nopadding_java中的 RSA加密

packagecom.cn.test.rsa;importjava.math.BigInteger;importjava.security.KeyFactory;importjava.security.KeyPair;importjava.security.KeyPairGenerator;importjava.security.NoSuchAlgorithmException;importjava.security.interfaces.RSAPrivateKey;importjava.security.interfaces.RSAPublicKey;importjava.security.spec.RSAPrivateKeySpec;importjava.security.spec.RSAPublicKeySpec;importjava.util.HashMap;importjavax.crypto.Cipher;public classRSAUtils {/*** 生成公钥和私钥

*@throwsNoSuchAlgorithmException

**/

public static HashMap getKeys() throwsNoSuchAlgorithmException{

HashMap map = new HashMap();

KeyPairGenerator keyPairGen= KeyPairGenerator.getInstance("RSA");

keyPairGen.initialize(1024);

KeyPair keyPair=keyPairGen.generateKeyPair();

RSAPublicKey publicKey=(RSAPublicKey) keyPair.getPublic();

RSAPrivateKey privateKey=(RSAPrivateKey) keyPair.getPrivate();

map.put("public", publicKey);

map.put("private", privateKey);returnmap;

}/*** 使用模和指数生成RSA公钥

* 注意:【此代码用了默认补位方式,为RSA/None/PKCS1Padding,不同JDK默认的补位方式可能不同,如Android默认是RSA

* /None/NoPadding】

*

*@parammodulus

* 模

*@paramexponent

* 指数

*@return

*/

public staticRSAPublicKey getPublicKey(String modulus, String exponent) {try{

BigInteger b1= newBigInteger(modulus);

BigInteger b2= newBigInteger(exponent);

KeyFactory keyFactory= KeyFactory.getInstance("RSA");

RSAPublicKeySpec keySpec= newRSAPublicKeySpec(b1, b2);return(RSAPublicKey) keyFactory.generatePublic(keySpec);

}catch(Exception e) {

e.printStackTrace();return null;

}

}/*** 使用模和指数生成RSA私钥

* 注意:【此代码用了默认补位方式,为RSA/None/PKCS1Padding,不同JDK默认的补位方式可能不同,如Android默认是RSA

* /None/NoPadding】

*

*@parammodulus

* 模

*@paramexponent

* 指数

*@return

*/

public staticRSAPrivateKey getPrivateKey(String modulus, String exponent) {try{

BigInteger b1= newBigInteger(modulus);

BigInteger b2= newBigInteger(exponent);

KeyFactory keyFactory= KeyFactory.getInstance("RSA");

RSAPrivateKeySpec keySpec= newRSAPrivateKeySpec(b1, b2);return(RSAPrivateKey) keyFactory.generatePrivate(keySpec);

}catch(Exception e) {

e.printStackTrace();return null;

}

}/*** 公钥加密

*

*@paramdata

*@parampublicKey

*@return*@throwsException*/

public staticString encryptByPublicKey(String data, RSAPublicKey publicKey)throwsException {

Cipher cipher= Cipher.getInstance("RSA");

cipher.init(Cipher.ENCRYPT_MODE, publicKey);//模长

int key_len = publicKey.getModulus().bitLength() / 8;//加密数据长度 <= 模长-11

String[] datas = splitString(data, key_len - 11);

String mi= "";//如果明文长度大于模长-11则要分组加密

for(String s : datas) {

mi+=bcd2Str(cipher.doFinal(s.getBytes()));

}returnmi;

}/*** 私钥解密

*

*@paramdata

*@paramprivateKey

*@return*@throwsException*/

public staticString decryptByPrivateKey(String data, RSAPrivateKey privateKey)throwsException {

Cipher cipher= Cipher.getInstance("RSA");

cipher.init(Cipher.DECRYPT_MODE, privateKey);//模长

int key_len = privateKey.getModulus().bitLength() / 8;byte[] bytes =data.getBytes();byte[] bcd =ASCII_To_BCD(bytes, bytes.length);

System.err.println(bcd.length);//如果密文长度大于模长则要分组解密

String ming = "";byte[][] arrays =splitArray(bcd, key_len);for(byte[] arr : arrays){

ming+= newString(cipher.doFinal(arr));

}returnming;

}/*** ASCII码转BCD码

**/

public static byte[] ASCII_To_BCD(byte[] ascii, intasc_len) {byte[] bcd = new byte[asc_len / 2];int j = 0;for (int i = 0; i < (asc_len + 1) / 2; i++) {

bcd[i]= asc_to_bcd(ascii[j++]);

bcd[i]= (byte) (((j >= asc_len) ? 0x00 : asc_to_bcd(ascii[j++])) + (bcd[i] << 4));

}returnbcd;

}public static byte asc_to_bcd(byteasc) {bytebcd;if ((asc >= '0') && (asc <= '9'))

bcd= (byte) (asc - '0');else if ((asc >= 'A') && (asc <= 'F'))

bcd= (byte) (asc - 'A' + 10);else if ((asc >= 'a') && (asc <= 'f'))

bcd= (byte) (asc - 'a' + 10);elsebcd= (byte) (asc - 48);returnbcd;

}/*** BCD转字符串*/

public static String bcd2Str(byte[] bytes) {char temp[] = new char[bytes.length * 2], val;for (int i = 0; i < bytes.length; i++) {

val= (char) (((bytes[i] & 0xf0) >> 4) & 0x0f);

temp[i* 2] = (char) (val > 9 ? val + 'A' - 10 : val + '0');

val= (char) (bytes[i] & 0x0f);

temp[i* 2 + 1] = (char) (val > 9 ? val + 'A' - 10 : val + '0');

}return newString(temp);

}/*** 拆分字符串*/

public static String[] splitString(String string, intlen) {int x = string.length() /len;int y = string.length() %len;int z = 0;if (y != 0) {

z= 1;

}

String[] strings= new String[x +z];

String str= "";for (int i=0; i

str= string.substring(i*len, i*len+y);

}else{

str= string.substring(i*len, i*len+len);

}

strings[i]=str;

}returnstrings;

}/***拆分数组*/

public static byte[][] splitArray(byte[] data,intlen){int x = data.length /len;int y = data.length %len;int z = 0;if(y!=0){

z= 1;

}byte[][] arrays = new byte[x+z][];byte[] arr;for(int i=0; i

arr= new byte[len];if(i==x+z-1 && y!=0){

System.arraycopy(data, i*len, arr, 0, y);

}else{

System.arraycopy(data, i*len, arr, 0, len);

}

arrays[i]=arr;

}returnarrays;

}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
RSA算法是一种非对称加密算法,其公钥可以用于加密数据,私钥则用于解密数据。而OAEP(Optimal Asymmetric Encryption Padding)是RSA算法加密时的一种填充方式,用于增加加密的安全性。在Java,可以使用Java Cryptography Extension(JCE)提供的API来实现RSA算法和OAEP填充方式的加密与解密操作。以下是一个使用RSA算法和OAEP填充方式进行加密Java示例代码: ```java import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.PublicKey; import java.security.PrivateKey; import javax.crypto.Cipher; public class RSAEncryptor { private static final String RSA_ALGORITHM = "RSA/ECB/OAEPWithSHA-256AndMGF1Padding"; public static void main(String[] args) throws Exception { String plainText = "Hello, world!"; KeyPair keyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair(); PublicKey publicKey = keyPair.getPublic(); PrivateKey privateKey = keyPair.getPrivate(); byte[] encryptedData = encrypt(plainText.getBytes(), publicKey); byte[] decryptedData = decrypt(encryptedData, privateKey); System.out.println("Plaintext: " + plainText); System.out.println("Encrypted data: " + new String(encryptedData)); System.out.println("Decrypted data: " + new String(decryptedData)); } public static byte[] encrypt(byte[] data, PublicKey publicKey) throws Exception { Cipher cipher = Cipher.getInstance(RSA_ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, publicKey); return cipher.doFinal(data); } public static byte[] decrypt(byte[] data, PrivateKey privateKey) throws Exception { Cipher cipher = Cipher.getInstance(RSA_ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, privateKey); return cipher.doFinal(data); } } ``` 在这个示例代码,我们使用KeyPairGenerator生成一个RSA密钥对,然后使用公钥加密一个字符串,最后使用私钥解密该字符串。注意,我们使用的RSA算法的填充方式为“OAEPWithSHA-256AndMGF1Padding”,这是一种较为安全的填充方式,可以提高加密的安全性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值