📄 hlencrsa.java
字号:
package HLEncRSA;import java.io.*;import java.math.*;import java.security.interfaces.*;public class HLEncRSA{//实现RSA加密类 private RSAPublicKey rsapPublicKey; private BigInteger mid_e,mid_n;//公钥e和n private String midEncString; private String EncString;//全部密文 private String sectString;//分段密文 private String message;//全部明文 private int TextPos;//全部明文中的指针 private byte ByteText[];//分段明文的"UTF-8"编码的字节数组 private int STextStartPos;//分段后,起始字节的位置(在ByteText[]) private int SegmentTextLength;//相对于密钥长度的最长的可加密字节数 public void readPublicKey(String keyPath){//读取加密密钥方法 try{ FileInputStream f=new FileInputStream(keyPath); ObjectInputStream b=new ObjectInputStream(f); RSAPublicKey pbk=(RSAPublicKey)b.readObject(); this.mid_e=pbk.getPublicExponent(); this.mid_n=pbk.getModulus(); this.rsapPublicKey=pbk; this.SegmentTextLength=mid_n.bitLength()/8-1;//先预留一字节 } catch(Exception e){} }//获取公钥 public String getMid_E(){ return mid_e.toString(); } public String getMid_N(){ return mid_n.toString(); } public void setMessage(String message){ this.message=message; this.TextPos=0; this.EncString="";//清空EncString } public String getSectString(){ return new String(sectString+"|"); } public String getEncString(){ return new String(EncString); } public int getByteTextLength(){ return ByteText.length; } public boolean nextSectUnencText(int sectLength) throws UnsupportedEncodingException{//取得下一分段明文 sectString=""; if(TextPos<message.length()){ int restUnencLength=message.length()-TextPos; int endPos=TextPos+(restUnencLength<sectLength? restUnencLength:sectLength);//分段的尾(在message中) //分段明文的字节数组 this.ByteText=message.substring(TextPos,endPos).getBytes("UTF-8"); //下一段明文的起点 TextPos=endPos; //明文字节的长度存放密文中 sectString+=Integer.toString(ByteText.length)+">"; // STextStartPos复位 this.STextStartPos=0; return true; } else return false; } public void froEncRsa(){//把分段加密得到的密文拼起来 this.EncString+=sectString+"|"; } public int EncRsa(int STextEndPos){//加密方法 int TextRestLength=ByteText.length-STextStartPos;//未加密的明文字节数 STextEndPos=STextStartPos+(TextRestLength>SegmentTextLength? SegmentTextLength:TextRestLength);//当前允许分段的长度 //形成分段明文字节数组,byte[0]=0; byte[] tempByteText=new byte[STextEndPos-STextStartPos+1]; tempByteText[0]='<';//初始化首位字节,不要空格 System.arraycopy(ByteText,STextStartPos, tempByteText,1,STextEndPos-STextStartPos); //下一段明文的起点 STextStartPos=STextEndPos; //把分段明文的字节数组转化成BigInteger类型 BigInteger bigint=new BigInteger(tempByteText); //利用e,n加密分段明文,并在密文尾插入分隔字符'>'(可其它字符) this.sectString+=bigint.modPow(mid_e,mid_n).toString()+'>'; return STextEndPos; } public void writeEncStringToFile()throws Exception{//把密文写入文件 this.midEncString=new String(this.EncString); //输出加密后的密文至文件HL_Enc_RSA.dat BufferedWriter out=new BufferedWriter(new OutputStreamWriter( new FileOutputStream("HL_Enc_RSA.dat"))); out.write(this.EncString,0,this.EncString.length( )); out.close( ); }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -