📄 liyuxin.java
字号:
import java.io.*;
import java.math.BigInteger;
import java.security.*;
import java.security.interfaces.*;
import java.security.spec.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import sun.misc.*;
import java.util.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import org.xml.sax.*;
public class liyuxin
{
public static void main(String[] args) //throws Exception
{
Rsa rsa =new Rsa();
KeyPair keypair=rsa.RsaKeyGen(512);
PublicKey pbkey=keypair.getPublic();
PrivateKey prkey=keypair.getPrivate();
//测试RsaEncrypt(String s,PrivateKey prkey)
System.out.println("Now we are going to use interface: 'RsaEncrypt(String s,PrivateKey prkey)' ");
String s1=rsa.RsaEncrypt("看萧萧暮雨洒江天一番洗清秋其实我也是很清楚到底是什么意思。",prkey);
System.out.println(" ");
System.out.println(" ");
//测试RsaEncrypt(File f);
System.out.println("Now we are going to use interface 'RsaEncrypt(File f)' ");
String s2 =rsa.RsaEncrypt((new File("ToBeEncrypted.xml")));
System.out.println(" ");
System.out.println(" ");
//测试RsaEncrypt(Doucument doc);
System.out.println("Now we are going to use interface 'RsaEncrypt(Document doc)'");
Document doc3=null;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try
{
DocumentBuilder builder = factory.newDocumentBuilder();
doc3=builder.parse(new File("ToBeEncrypted.xml"));
}
catch(ParserConfigurationException e)
{
e.printStackTrace();
}
catch(SAXException e)
{
e.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
String s3=rsa.RsaEncrypt(doc3);
System.out.println(" ");
System.out.println(" ");
if(rsa.RsaDecrypt("看萧萧暮雨洒江天一番洗清秋其实我也是很清楚到底是什么意思。",pbkey,s1))
{
System.out.println("Congratulations ,Siganature is just cheched by the PublicKey provided ,no problem!");
}
else
{
System.out.println("I am sorry ,but the Signature is not correct when checked by the PublicKey .");
}
//测试接口RsaDecrypt(Document doc)
Document doc5=null;
factory = DocumentBuilderFactory.newInstance();//前面已经定义了。
try
{
DocumentBuilder builder = factory.newDocumentBuilder();
//System.out.println(doc5.getInputEncoding());
doc5=builder.parse(new File("ToBeDecrypted.xml"));
}
catch(ParserConfigurationException e)
{
e.printStackTrace();
}
catch(SAXException e)
{
e.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
System.out.println("Now we are going to use interface 'RsaDecrypt(Document doc)'");
if(rsa.RsaDecrypt(doc5))
{
System.out.println("Congratulations ,Siganature is just cheched by the PublicKey provided ,no problem!");
}
else
{
System.out.println("I am sorry ,but the Signature is not correct when checked by the PublicKey .");
}
System.out.println(" ");
System.out.println(" ");
//测试接口RsaDecrypt(File f)
System.out.println("Now we are going to use interface 'RsaDecrypt(Document doc)'");
if(rsa.RsaDecrypt(new File("ToBeDecrypted.xml")))
{
System.out.println("Congratulations ,Siganature is just cheched by the PublicKey provided ,no problem!");
}
else
{
System.out.println("I am sorry ,but the Signature is not correct when checked by the PublicKey .");
}
System.out.println(" ");
System.out.println(" ");
//测试接口RsaDecrypt(String s,PublicKey key,String c)
}
}
class Rsa
{
public Rsa()
{
RsaInstance=new RichRSACipher();
try
{
CurrentDigest=MessageDigest.getInstance("SHA-1");
}
catch(NoSuchAlgorithmException e)
{
e.printStackTrace();
}
try
{
kpg=KeyPairGenerator.getInstance("RSA");
}
catch(NoSuchAlgorithmException e)
{
e.printStackTrace();
}
}
protected KeyPair RsaKeyGen(int KeySizeNeeded)//生成密钥对
{
if(KeySizeNeeded<512)
{
System.out.println("KeysizeNeeded is too small,choose larger one ,please!");
return null;
}
if(KeySizeNeeded>2048)
{
System.out.println("KeysizeNeeded is too large,choose a smaller one ,please!");
return null;
}
if(KeySizeNeeded<512)
{
System.out.println("KeySizeNeeded is not valide ,it must be Multiply of 8,choose another one");
return null;
}
kpg.initialize(KeySizeNeeded);
KeyPair kp=kpg.genKeyPair();
return kp;
}//生成密钥对
//以下算法返回一个doc对象,该doc内含了该xml文档.
protected String RsaEncrypt(String OrignalString,PrivateKey prkey) //throws Exception
{
System.out.println("OrignalMessage is: "+OrignalString);
//System.out.println("Message.length is: "+OrignalString.length());
try
{
OrignalByte=OrignalString.getBytes("UNICODE");
}
catch(UnsupportedEncodingException e)
{
e.printStackTrace();
}
//以下为提取unicode编码的头两个字节,在加密完返回字符串的时候添加在密文的头部,这样才可将数组转换成字符串(unicode编码需要头部)
UnicodeStringHead=new byte[2];
System.arraycopy(OrignalByte,0,UnicodeStringHead,0,2);
//先转换成摘要MByte
CurrentDigest.reset();
//long time1=(new GregorianCalendar()).getTimeInMillis();//该语句为测试的时候加上的。可以不要
CurrentDigest.update(OrignalByte);
MByte=CurrentDigest.digest();
//long time2=(new GregorianCalendar()).getTimeInMillis();//该语句为测试的时候加上的。可以不要
//System.out.println("DigestTime is "+(time2-time1));//该语句为测试的时候加上的。可以不要
byte[] HeadAddedDigestStringByte=new byte[MByte.length+2];
System.arraycopy(UnicodeStringHead,0,HeadAddedDigestStringByte,0,2);
System.arraycopy(MByte,0,HeadAddedDigestStringByte,2,MByte.length);
try
{
HeadAddedDigestString =new String(HeadAddedDigestStringByte,"UTF-8");
}
catch(UnsupportedEncodingException e)
{
e.printStackTrace();
}
TempRandom =new SecureRandom();//安全系数很高的随机类
//本方法是密钥初始化RsaInstance
try
{
RsaInstance.engineInit(Cipher.ENCRYPT_MODE,prkey,(RSAKeyGenParameterSpec)null,TempRandom);
}
catch(InvalidKeyException e)
{
e.printStackTrace();
}
catch(InvalidAlgorithmParameterException e)
{
e.printStackTrace();
}
outsize=0;
offset=0;
BlockSize=RsaInstance.engineGetBlockSize();
if(MByte.length>=BlockSize)
{
TempByte=new byte[(int)(MByte.length*(BlockSize+11)/BlockSize+1)];
}
else
{
TempByte=new byte[BlockSize+11];
}
// (s.length()*2+2)为该字符串的unicode编码的字节数,*(BlockSize+11)/BlockSize是因为padding格式需要留出至少十个空位,
//加上必须保证加密的块比模数小,所以再空出一位,所以需要
for(;MByte.length-offset>=BlockSize;offset=offset+BlockSize)
{
byte[] TempOutByte=RsaInstance.engineUpdate(MByte,offset,BlockSize);
System.arraycopy(TempOutByte,0,TempByte,outsize,TempOutByte.length);
outsize=outsize+TempOutByte.length;
//System.out.println("outsize is "+ outsize);
}//前几次满块加密,即从摘要数组中每次提取能加密/解密的最大块,去进行加密/解密操作
byte [] TempOutByte2=null;
if(MByte.length-offset>0)//如果摘要数组不是能一次加密的最大块的整数倍,则MByte.length-offset>0
{
TempOutByte2=RsaInstance.engineUpdate(MByte,offset,MByte.length-offset);//最后一次非满块加密
System.arraycopy(TempOutByte2,0,TempByte,outsize,TempOutByte2.length);
}
if( TempOutByte2!=null)
{
outsize=outsize+TempOutByte2.length;
}
CByte=new byte[outsize];
System.arraycopy(TempByte,0,CByte,0,outsize);
try
{
finals=new String(CByte,"UNICODE");
}
catch(UnsupportedEncodingException e)
{
e.printStackTrace();
}
//添加unicode码的头部,这样好转换成字符串
byte[] HeadAddedByte=new byte[outsize+2];
System.arraycopy(UnicodeStringHead,0,HeadAddedByte,0,2);
System.arraycopy(CByte,0,HeadAddedByte,2,outsize);
try
{
HeadAddedCText =new String(HeadAddedByte,"UTF-8");//转换成该编码格式的,因为生成的xml文档是故UTF-8格式的
}
catch(UnsupportedEncodingException e)
{
e.printStackTrace();
}
//System.out.println("HeadAddedCText is "+HeadAddedCText);
System.out.println(" SignatureValue is: "+HeadAddedCText);
/* System.out.println(HeadAddedCText.length());
System.out.println(OrignalString.length());
System.out.println(BlockSize);
return HeadAddedCText;
*/
/* System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("now decrpyt");
if(this.RsaDecrypt(OrignalString,pbkey,finals))
System.out.println("success!");
else
System.out.println("sorry");
*/
return finals;
/* ///////////////////////////////////////////////////////////2006.06.14///////////////////////////////////////////////
factory = DocumentBuilderFactory.newInstance();
try
{
builder = factory.newDocumentBuilder();
}
catch(javax.xml.parsers.ParserConfigurationException e)
{
e.printStackTrace();
}
//if(builder==null) System.out.println("null builder");
doc=builder.newDocument();
if (doc==null) System.out.println("null doc");
Element SignatureElement=doc.createElement("Signature");
doc.appendChild(SignatureElement);
doc.createProcessingInstruction("encoding","UTF-8");
Element SignedInfoElement=doc.createElement("SignedInfo");
SignatureElement.appendChild(SignedInfoElement);
Element CanonicalizationMethodElement=doc.createElement("CanonicalizationMethod");
CanonicalizationMethodElement.setAttribute("Algorithm","http://www.w3.org/TR/2001/REC-xml-c14n-20010315");
SignedInfoElement.appendChild(CanonicalizationMethodElement);
Element SignatureMethodElement=doc.createElement("SignatureMethod");
SignatureMethodElement.setAttribute("Algorithm","http://www.w3.org/2000/09/xmldsig#rsa-sha1");
SignedInfoElement.appendChild(SignatureMethodElement);
Element ReferenceElement=doc.createElement("Reference");
ReferenceElement.setAttribute("URI","http://www.w3.org/TR/xml-stylesheet");
ReferenceElement.setAttribute("URI","http://www.w3.org/2000/09/xmldsig#sha1");
SignedInfoElement.appendChild(ReferenceElement);
Element DigestMethodElement=doc.createElement("DigestMethod");
DigestMethodElement.setAttribute("Algorithm","http://www.w3.org/2000/09/xmldsig#sha1");
ReferenceElement.appendChild(DigestMethodElement);
/* Element DigestValueElement=doc.createElement("DigestValue");
Text DigestValue=doc.createTextNode(HeadAddedDigestString);
//System.out.println("HeadAddedDigestString is "+HeadAddedDigestString);
DigestValueElement.appendChild(DigestValue);
ReferenceElement.appendChild(DigestValueElement);//该节点不必要,not needed。
*/
/**////////////////////////////////////////////////////////////2006.06.14///////////////////////////////////////////////
/*///////////////////////////////////////////////////////////2006.06.14///////////////////////////////////////////////
Element SignatureValueElement=doc.createElement("SignatureValue");
Text SignatureValue=doc.createTextNode(HeadAddedCText);
SignatureValueElement.appendChild(SignatureValue);
SignatureElement.appendChild(SignatureValueElement);
//不然都从xml文档里取密钥,非常容易冒充。
Element KeyInfoElement=doc.createElement("KeyInfo");
Element KeyValueElement=doc.createElement("KeyValue");
Element RSAKeyValueElement=doc.createElement("RSAKeyValue");
Element ModulusElement=doc.createElement("Modulus");
Text ModulusValue=doc.createTextNode("");//空节点。不必要
ModulusElement.appendChild(ModulusValue);
RSAKeyValueElement.appendChild(ModulusElement);
Element ExponentElement=doc.createElement("Exponent");
Text ExponentValue=doc.createTextNode("");//空节点,不必要
ExponentElement.appendChild(ExponentValue);
RSAKeyValueElement.appendChild(ExponentElement);
KeyValueElement.appendChild(RSAKeyValueElement);
KeyInfoElement.appendChild(KeyValueElement);
Element X509DataElement=doc.createElement("X509Data");
Element X509SubjectNameElement=doc.createElement("X509SubjectName");
Text X509SubjectNameValue=doc.createTextNode("");
X509SubjectNameElement.appendChild(X509SubjectNameValue);
X509DataElement.appendChild(X509SubjectNameElement);
Element X509IssuerSerialElement=doc.createElement("X509IssuerSerial");
Element X509IssuerNameElement=doc.createElement("X509IssuerName");
Text X509IssuerNameValue=doc.createTextNode("");
X509IssuerNameElement.appendChild(X509IssuerNameValue);
X509IssuerSerialElement.appendChild(X509IssuerNameElement);
Element X509SerialNumberElement=doc.createElement("X509SerialNumber");
Text X509SerialNumberValue=doc.createTextNode("");
X509SerialNumberElement.appendChild(X509SerialNumberValue);
X509IssuerSerialElement.appendChild(X509SerialNumberElement);
X509DataElement.appendChild(X509IssuerSerialElement);
Element X509CertificateElement=doc.createElement("X509Certificate");
X509DataElement.appendChild(X509CertificateElement);
KeyInfoElement.appendChild(X509DataElement);//该节点都不必要
SignatureElement.appendChild(KeyInfoElement);
f=new File("EcryptedToLiyuxin.xml");
try
{
t =TransformerFactory.newInstance().newTransformer();
}
catch(TransformerConfigurationException e)
{
e.printStackTrace();
}
t.setOutputProperty("doctype-public","http://www.w3.org/TR/2000/CR-SVG-20000802/DTD/svg-20000802.dtd");
t.setOutputProperty("doctype-public","-//W3C//DTD SVG 20000802//EN");
t.setOutputProperty("indent","yes");
try
{
if (doc==null) System.out.println("null doc");
doc.createProcessingInstruction("encoding","UNICODE");
//t.transform(new DOMSource(doc),new StreamResult(new FileOutputStream(f)));
DOMSource domsource=new DOMSource(doc);
StreamResult streamresult=new StreamResult(new FileOutputStream(f));
if (domsource==null) System.out.println("null domsource");
if (streamresult==null)System.out.println("null streamresult");
t.transform(domsource,streamresult);
}
catch(TransformerConfigurationException e)
{
e.printStackTrace();
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
catch(TransformerException e)
{
e.printStackTrace();
}
//根结点的三个子结点
return doc;
*////////////////////////////////////////////////////////////2006.06.14///////////////////////////////////////////////
}//RsaEncrypt(String OrignalString,PrivateKey prkey)结束
//以下这个接口不再使用,因为编写代码时一步步扩展,后来把privatekey放在了文件f中
/*///////////////////////////////////////////////////////////2006.06.14///////////////////////////////////////////////
protected Document RsaEncrypt(File f,PrivateKey prkey)
{ Document doc=null;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try
{
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -