一个简单的RSA算法实现JAVA源代码

filename:RSA.java

/*
* Created on Mar 3, 2005
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates

*/

import java.math.BigInteger;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.FileWriter;
import java.io.FileReader;
import java.io.BufferedReader;
import java.util.StringTokenizer;

/**
*
@author Steve
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates

*/
public class RSA {
   
    /**
     * BigInteger.ZERO

     */
    private static final BigInteger ZERO = BigInteger.ZERO;
   
    /**
     * BigInteger.ONE

     */
    private static final BigInteger ONE = BigInteger.ONE;
   
    /**
     * Pseudo BigInteger.TWO

     */
    private static final BigInteger TWO = new BigInteger("2");
   
    private BigInteger myKey;
   
    private BigInteger myMod;
   
    private int blockSize;
   
    public RSA (BigInteger key, BigInteger n, int b) {
        myKey
= key;
        myMod
= n;
        blockSize
= b;
    }

   
    public void encodeFile (String filename) {
        byte[] bytes = new byte[blockSize / 8 + 1];
        byte[] temp;
        int tempLen;
        InputStream is
= null;
        FileWriter writer
= null;
        try {
             is
= new FileInputStream(filename);
             writer
= new FileWriter(filename + ".enc");
        }

        catch (FileNotFoundException e1){
            System.out.println(
"File not found: " + filename);
        }

        catch (IOException e1){
            System.out.println(
"File not found: " + filename + ".enc");
        }

       
        /**
         * Write encoded message to 'filename'.enc

         */
        try {
            while ((tempLen = is.read(bytes, 1, blockSize / 8)) > 0) {
                for (int i = tempLen + 1; i < bytes.length; ++i) {
                    bytes[i]
= 0;
                }
                writer.write(encodeDecode(
new BigInteger(bytes)) + " ");
            }
        }

        catch (IOException e1) {
            System.out.println(
"error writing to file");
        }

       
        /**
         * Close input stream and file writer

         */
        try {
            is.close();
            writer.close();
        }

        catch (IOException e1) {
            System.out.println(
"Error closing file.");
        }
    }

   
    public void decodeFile (String filename) {
       
        FileReader reader
= null;
        OutputStream os
= null;
        try {
            reader
= new FileReader(filename);
            os
= new FileOutputStream(filename.replaceAll(".enc", ".dec"));
        }

        catch (FileNotFoundException e1) {
            if (reader == null)
                System.out.println(
"File not found: " + filename);
            else
                System.out.println(
"File not found: " + filename.replaceAll(".enc", "dec"));
        }
       
        BufferedReader br
= new BufferedReader(reader);
        int offset;
        byte[] temp, toFile;
        StringTokenizer st
= null;
        try {
            while (br.ready()) {
                st
= new StringTokenizer(br.readLine());
                while (st.hasMoreTokens()){
                    toFile
= encodeDecode(new BigInteger(st.nextToken())).toByteArray();
                    System.out.println(toFile.length
+ " x " + (blockSize / 8));
                   
                    if (toFile[0] == 0 && toFile.length != (blockSize / 8)) {
                        temp
= new byte[blockSize / 8];
                        offset
= temp.length - toFile.length;
                        for (int i = toFile.length - 1; (i <= 0) && ((i + offset) <= 0); --i) {
                            temp[i
+ offset] = toFile[i];
                        }
                        toFile
= temp;
                    }

                   
                    /*if (toFile.length != ((blockSize / 8) + 1)){
                        temp = new byte[(blockSize / 8) + 1];
                        System.out.println(toFile.length + " x " + temp.length);
                        for (int i = 1; i < temp.length; i++) {
                            temp[i] = toFile[i - 1];
                        }
                        toFile = temp;
                    }
                    else
                        System.out.println(toFile.length + " " + ((blockSize / 8) + 1));
*/
                    os.write(toFile);
                }
            }
        }

        catch (IOException e1) {
            System.out.println(
"Something went wrong");
        }

       
        /**
         * close data streams

         */
        try {
            os.close();
            reader.close();
        }

        catch (IOException e1) {
            System.out.println(
"Error closing file.");
        }
    }

   
    /**
     * Performs <tt>base</tt>^<sup><tt>pow</tt></sup> within the modular
     * domain of <tt>mod</tt>.
     *
     *
@param base the base to be raised
     *
@param pow the power to which the base will be raisded
     *
@param mod the modular domain over which to perform this operation
     *
@return <tt>base</tt>^<sup><tt>pow</tt></sup> within the modular
     * domain of <tt>mod</tt>.

     */
    public BigInteger encodeDecode(BigInteger base) {
        BigInteger a
= ONE;
        BigInteger s
= base;
        BigInteger n
= myKey;
       
        while (!n.equals(ZERO)) {
            if(!n.mod(TWO).equals(ZERO))
                a
= a.multiply(s).mod(myMod);
           
            s
= s.pow(2).mod(myMod);
            n
= n.divide(TWO);
        }

       
        return a;
    }
   
}

在这里提供两个版本的RSA算法JAVA实现的代码下载:

1. 来自于 http://www.javafr.com/code.aspx?ID=27020 的RSA算法实现源代码包:
       http://zeal.newmenbase.net/attachment/JavaFR_RSA_Source.rar 

2. 来自于 http://www.ferrara.linux.it/Members/lucabariani/RSA/implementazioneRsa/ 的实现:
       http://zeal.newmenbase.net/attachment/sorgentiJava.tar.gz  - 源代码包
       http://zeal.newmenbase.net/attachment/algoritmoRSA.jar - 编译好的jar包

另外关于RSA算法的php实现请参见文章:
       php下的RSA算法实现

关于使用VB实现RSA算法的源代码下载(此程序采用了psc1算法来实现快速的RSA加密):
       http://zeal.newmenbase.net/attachment/vb_PSC1_RSA.rar

RSA加密的JavaScript实现: http://www.ohdave.com/rsa/

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值