📄 liyuxin.java
字号:
}
catch(UnsupportedEncodingException e)
{
e.printStackTrace();
}
return false;
}//RsaDecrypt(String s,PublicKey pbkey,String c)
protected boolean RsaDecrypt(File f)
{
Document MessaageDoc=null;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try
{
DocumentBuilder builder = factory.newDocumentBuilder();
MessaageDoc=builder.parse(f);
}
catch(ParserConfigurationException e)
{
e.printStackTrace();
}
catch(SAXException e)
{
e.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
boolean returnvalue=this.RsaDecrypt(MessaageDoc);
return returnvalue;
}
protected boolean RsaDecrypt(Document MessageDoc)
{
NodeList ExponentNodeList=MessageDoc.getElementsByTagName("PublicExponent");
NodeList ModulusNodeList=MessageDoc.getElementsByTagName("Modulus");
NodeList MessageValueNodeList=MessageDoc.getElementsByTagName("MessageValue");
NodeList SignatureValueNodeList=MessageDoc.getElementsByTagName("SignatureValue");
if(ExponentNodeList.getLength()!=1)
{
System.out.println("Invalid xml file,check exponent node ,please");
}
if(ExponentNodeList.getLength()!=1)
{
System.out.println("Invalid xml file,check exponent node ,please");
}
String ExponentString=ExponentNodeList.item(0).getFirstChild().getNodeValue();
String ModulusString = ModulusNodeList.item(0).getFirstChild().getNodeValue();
String s =MessageValueNodeList.item(0).getFirstChild().getNodeValue();
String c=SignatureValueNodeList.item(0).getFirstChild().getNodeValue();
//System.out.println(ExponentString);
//System.out.println(ModulusString);
//System.out.println(s);
//测试用的,保留。
System.out.println("c is " +c);
BigInteger Exponent=new BigInteger(ExponentString);
BigInteger Modulus =new BigInteger(ModulusString);
CurrentDigest.reset();//准备摘要
try
{
byte[] TempByteInDecrypt=s.getBytes("UNICODE");
CurrentDigest.update(TempByteInDecrypt);
DigestByte=CurrentDigest.digest();//用来比较的
}
catch(UnsupportedEncodingException e)
{
e.printStackTrace();
}
//以下为对签名进行解密的部分
//去掉字符串的头部,即为了显示而加上去的unicode编码的头部。
CByte=new byte[c.length()*2];
try
{
System.arraycopy(c.getBytes("UNICODE"),0,CByte,0,CByte.length);
}
catch(UnsupportedEncodingException e)
{
e.printStackTrace();
}
try
{
RsaInstance.newengineInit(Cipher.DECRYPT_MODE,Exponent,Modulus,(RSAKeyGenParameterSpec)null,new SecureRandom());
}
catch(InvalidKeyException e)
{
e.printStackTrace();
}
catch(InvalidAlgorithmParameterException e)
{
e.printStackTrace();
}
BlockSize=RsaInstance.engineGetBlockSize();
outsize=0;
offset=0;
SecondTempByte=new byte[CByte.length];
if(CByte.length%BlockSize != 0)
{
System.out.println("the message to be decrypted is invalid");
System.exit(0);
}
System.out.println("CByte.length is "+CByte.length);
for(;CByte.length-offset>=BlockSize;offset=offset+BlockSize)
{
byte[] SecondTempOutByte=RsaInstance.engineUpdate(CByte,offset,BlockSize);
System.arraycopy(SecondTempOutByte,0,SecondTempByte,outsize,SecondTempOutByte.length);
outsize=outsize+SecondTempOutByte.length;
}
SecondCByte=new byte[outsize];
System.arraycopy(SecondTempByte,0,SecondCByte,0,outsize);
//以下进行比较
try
{
String tempStringOne=new String(SecondTempByte,"UNICODE");
String tempStringTwo=new String(DigestByte,"UNICODE");
if(tempStringOne.equals(tempStringTwo))
return true;
}
catch(UnsupportedEncodingException e)
{
e.printStackTrace();
}
return false;
}
//**************************
//成员变量如下
private RichRSACipher RsaCipher;
//private String s;
private byte[] OrignalByte;
private byte[] MByte;
private byte[] TempByte;
//in Decrypt
private byte[] CByte;
private byte[] DigestByte;
private byte[] SecondTempByte;
private byte[] SecondCByte;
//
private MessageDigest CurrentDigest;
private RichRSACipher RsaInstance;
private KeyPairGenerator kpg;
private SecureRandom TempRandom;
private PublicKey pbkey;
private PrivateKey prkey;
private int BlockSize;
private int offset=0;
private final boolean TESTNEEDED=false;
private int outsize=0;
private String finals;
private byte[] UnicodeStringHead;
private Document doc;
private DocumentBuilderFactory factory;
private DocumentBuilder builder;
private Transformer t;
private StreamResult stream;
private String HeadAddedCText;
private String HeadAddedDigestString;
private File f;
private TransformerFactory transfactory;
private String DigestValueString;
}
//主类rsa完成
//以下为RichRSACipher类。
class RichRSACipher extends CipherSpi
{
private RSAKeyGenParameterSpec params_;//该类对象用来接收rsa算法的密钥对生成参数:即密钥长度和模数.
//该类有一个方法public RSAKeyGenParameterSpec(int keysize, BigInteger publicExponent)
private SecureRandom random_;
private final static boolean TESTNEEDED = false;
private int opmode_;//有四种模式:ENCRYPT_MODE(加密)DECRYPT_MODE(解密)WRAP_MODE(包装)UNWRAP_MODE(解包)
//后两种用于利用一个密钥对另一个密钥加密.
private Key key_;
private byte[] internal_buffer_;//每次把要加密/解密的内容存在该数组去加密/解密。
private int KeyInited=0;
private int IntegerInited=0;
private BigInteger Modulus;
private BigInteger Exponent;
// 构造函数为空函数,因为有专门的初始化方法。
RichRSACipher() {}
/**
* Method engineDoFinal
* Description: See CipherSpi
*/
protected byte[] engineDoFinal(
byte[] input, int inputOffset, int inputLen)
throws IllegalBlockSizeException,
BadPaddingException
{
byte[] output = engineUpdate(input, inputOffset, inputLen);
internal_buffer_ = null;
return output;
}
// 见 CipherSpi类里的抽象方法,实现该抽象方法。跟engineupdate一致。
protected int engineDoFinal( byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset)
throws ShortBufferException,
IllegalBlockSizeException,
BadPaddingException
{
byte[] buffer;
buffer = engineDoFinal(input, inputOffset, inputLen);
if (output.length - outputOffset < buffer.length)
{
throw new ShortBufferException(
"Output longer than buffer");
}
System.arraycopy(buffer, 0, output, outputOffset, buffer.length);
return buffer.length;
}
//获取一次可加密解密的块的最大大小。
protected int engineGetBlockSize()
{
if ((opmode_ == Cipher.ENCRYPT_MODE)
|| (opmode_ == Cipher.WRAP_MODE))
{
return params_.getKeysize()-11;//填充模式需要至少十个位,加上是加密必须小于模数空出一个位置,所以是十一个.
//**********************************************************
//减1是我自己写的,原来的函数没有减1,应该需要减1.
}
else
{
return params_.getKeysize() ;
}
}
//该方法不需要,但是得实现,因为父类中抽象方法。
protected byte[] engineGetIV()
{
return null; // If not supported 本算法不需要此项,该函数是父类的抽象函数,必须实现的.所以可以什么也不干,因为不会用到.
}
//该方法不需要,但是得实现,因为父类中抽象方法。
protected int engineGetKeySize(Key key)
throws InvalidKeyException
{
/*
* Get the key size based on bit length
*/
if (key instanceof RSAPrivateKey)
{
RSAPrivateKey k = (RSAPrivateKey) key;
return k.getModulus().bitLength();
}
else if (key instanceof RSAPublicKey)
{
RSAPublicKey k = (RSAPublicKey) key;
return k.getModulus().bitLength();
}
throw new InvalidKeyException("Unsupported RSA key!");
}
//该方法不需要,但是得实现,因为父类中抽象方法。
protected int engineGetOutputSize(int inputLen)
{
if ((opmode_ == Cipher.ENCRYPT_MODE)
|| (opmode_ == Cipher.WRAP_MODE))
{
return params_.getKeysize();
}
else
{
return params_.getKeysize() - 1;
}
}
//该方法不需要,但是得实现,因为父类中抽象方法。
protected AlgorithmParameters engineGetParameters()
{
return null;
}//not supported!
//初始化,用密钥初始化。
//random参数在填充的时候需要
//_key 为公钥或者私钥
//opmode为解密模式或者加密模式
protected void engineInit(
int opmode, Key _key, AlgorithmParameterSpec params, SecureRandom _random)
throws InvalidKeyException,
InvalidAlgorithmParameterException
{
KeyInited=1;
IntegerInited=0;
// 密钥必须为这两种里的一种
if ((!(_key instanceof RSAPublicKey)) && (!(_key instanceof RSAPrivateKey)))
{
throw new InvalidKeyException("Unsupported RSA Key!");
}
// 可以为RSAKeyGenParameterSpec或者为空,但是不能为其他值
if ((params != null)
&& (!(params instanceof RSAKeyGenParameterSpec)))
{
throw new InvalidAlgorithmParameterException("Unsupported RSA AlgorithmParameterSpec!");
}
// 初始化 params实例字段
if (params != null)
{
params_ = (RSAKeyGenParameterSpec) params;
}
else
{
int keysize = 0;
BigInteger publicExp = Exponent;
if (_key instanceof RSAPublicKey)
{
publicExp = ((RSAPublicKey) _key).getPublicExponent();
int modulusLength =
((RSAPublicKey) _key).getModulus().bitLength();
keysize = (modulusLength + 7) / 8;//为填充做准备.keysize为字节数
}
else if (_key instanceof RSAPrivateKey)
{
int modulusLength =
((RSAPrivateKey) _key).getModulus().bitLength();
keysize = (modulusLength + 7) / 8;
}
if(TESTNEEDED){
System.out.println("RichRSACipher:engineInit:keysize:" + keysize);
}
params_ = new RSAKeyGenParameterSpec(keysize, publicExp);
}
random_ = _random;
// Check for valid types of opmode
if ((opmode == Cipher.DECRYPT_MODE)
|| (opmode == Cipher.ENCRYPT_MODE))
{
if (((opmode == Cipher.DECRYPT_MODE) || (opmode == Cipher
.UNWRAP_MODE)) && (_key instanceof RSAPrivateKey))
{
throw new InvalidKeyException(
"Unsupported: Decrypt/UnWrap mode must use RSAPublicKey");
}
if (((opmode == Cipher.ENCRYPT_MODE) || (opmode == Cipher
.WRAP_MODE)) && (_key instanceof RSAPublicKey))
{
throw new InvalidKeyException(
"Unsupported: Encrypt/Wrap mode must use RSAPrivateKey");
}
if(TESTNEEDED){
if ((opmode == Cipher.DECRYPT_MODE) || (opmode == Cipher.UNWRAP_MODE)){
System.out.println("RichRSACipher:engineInit:DECRYPT_MODE");
}else{
System.out.println("RichRSACipher:engineInit:ENCRYPT_MODE");
}
}
}
else
{
throw new InvalidKeyException("Unsupported opmode!");
}
opmode_ = opmode;
key_ = _key;
}
//父类中该方法就是重载方法,为了省事,让它们调用就好了。
protected void engineInit(
int opmode, Key _key, AlgorithmParameters params, SecureRandom _random)
throws InvalidKeyException,
InvalidAlgorithmParameterException
{
engineInit(opmode, _key, (AlgorithmParameterSpec) null,
_random);
}
//父类中该方法就是重载方法,为了省事,让它们调用就好了。
protected void engineInit(
int opmode, Key _key, SecureRandom _random)
throws InvalidKeyException
{
try
{
engineInit(opmode, _key, (AlgorithmParameterSpec) null,
_random);
}
catch (InvalidAlgorithmParameterException ex)
{
throw new InvalidKeyException(ex.getMessage());
}
}
//用两大数字代替密钥初始化该类 ,模数和指数
protected void newengineInit( int opmode, BigInteger e,BigInteger n, AlgorithmParameterSpec params, SecureRandom _random)
throws InvalidAlgorithmParameterException ,InvalidKeyException
{
IntegerInited=1;
KeyInited=0;
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -