java字符串转biginteger_RSA将字符串转换为BigInteger

我正在使用RSA算法程序并试图让它接受一个字符串作为消息而不是数字。我以为我的转换是正确的,但是当我跑步时出现错误,有人能看出原因吗?

import java.math.BigInteger;

import java.security.SecureRandom;

public class rsa {

//declaring random for use in pub and private gen

private final static SecureRandom random = new SecureRandom();

//declarring bigInts

private BigInteger privateKey;

private BigInteger publicKey;

private BigInteger modulus;

// generate an N-bit (roughly) public and private key

rsa(int N) {

BigInteger p = BigInteger.probablePrime(N/2, random);

BigInteger q = BigInteger.probablePrime(N/2, random);

BigInteger phi = p.subtract(BigInteger.valueOf(1));

phi = phi.multiply(q.subtract(BigInteger.valueOf(1)));

modulus = p.multiply(q);

publicKey = new BigInteger("65537"); // common value in practice = 2^16 + 1

privateKey = publicKey.modInverse(phi);

}

//encrypting function

BigInteger encrypt(BigInteger message) {

return message.modPow(publicKey, modulus);

}

//decrypting function

BigInteger decrypt(BigInteger encrypted) {

return encrypted.modPow(privateKey, modulus);

}

//printing values

public String toString() {

String s = "";

s += "public = " + publicKey + "\n";

s += "private = " + privateKey + "\n";

s += "modulus = " + modulus;

return s;

}

public static void main(String[] args) {

//declaring n (numbrer of bytes)

int N = 128;

//new object key RSA

rsa key = new rsa(N);

//printing the key

System.out.println("key = " + key);

// create message by converting string to integer

String s = "test";

byte[] bytes = s.getBytes();

BigInteger message = new BigInteger(s);

//encryting message

BigInteger encrypt = key.encrypt(message);

//decrypting encryption

BigInteger decrypt = key.decrypt(encrypt);

//printing values

System.out.println("message = " + message);

System.out.println("encrpyted = " + encrypt);

System.out.println("decrypted = " + decrypt);

}

}

这就是我得到的错误

Exception in thread "main" java.lang.NumberFormatException: For input string: "test"

at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)

at java.lang.Integer.parseInt(Integer.java:580)

at java.math.BigInteger.(BigInteger.java:461)

at java.math.BigInteger.(BigInteger.java:597)

at rsa.main(rsa.java:64)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值