JAVA RSA非対称セグメント復号化

39021 ワード

私は原理を言わない
https://blog.csdn.net/linuxandroidwince/article/details/81141815 原理の点を見て
ダイレクトコード
鍵ペアが生成され、プロジェクトルートディレクトリがファイルを生成します.印刷された秘密鍵や公開鍵を直接取り出すこともできます
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;

import sun.misc.BASE64Encoder;//jdk1.8       
/**
     *        RSA
     */
    private static final String ALGORITHM = "RSA";
    /**
     *     ,     
     */
    private static final int KEYSIZE = 1024;
    /**
     *         
     */
    private static String PUBLIC_KEY_FILE = "PublicKey";
    /**
     *         
     */
    private static String PRIVATE_KEY_FILE = "PrivateKey";
    

    public static void main(String[] args) throws Exception {
        generateKeyPair();
    }

    /**
     *         
     *
     * @throws Exception
     */
    private static void generateKeyPair() throws Exception {

        /** RSA                */
        /**  RSA      KeyPairGenerator   */
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM);

        /**                KeyPairGenerator   */
        keyPairGenerator.initialize(KEYSIZE);

        /**       */
        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        /**      */
        Key publicKey = keyPair.getPublic();

        /**      */
        Key privateKey = keyPair.getPrivate();
        
        byte[] publicKeyBytes = publicKey.getEncoded();
        byte[] privateKeyBytes = privateKey.getEncoded();

        String publicKeyBase64 = new BASE64Encoder().encode(publicKeyBytes);
        String privateKeyBase64 = new BASE64Encoder().encode(privateKeyBytes);

        System.out.println("      :" + publicKeyBase64.length());
        System.out.println("    :" + publicKeyBase64);

        System.out.println("      :" + privateKeyBase64.length());
        System.out.println("    :" + privateKeyBase64);
        
        ObjectOutputStream oos1 = null;
        ObjectOutputStream oos2 = null;
        try {
            /**                */
            oos1 = new ObjectOutputStream(new FileOutputStream(PUBLIC_KEY_FILE));
            oos2 = new ObjectOutputStream(new FileOutputStream(PRIVATE_KEY_FILE));
            oos1.writeObject(publicKey);
            oos2.writeObject(privateKey);
        } catch (Exception e) {
            throw e;
        } finally {
            /**     ,        */
            oos1.close();
            oos2.close();
        }
    }

データ長が長すぎるとエラーが発生します.これはセグメント暗号化が必要です.
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.security.Key;
import javax.crypto.Cipher;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class RSAUtil {
	/**        RSA */
    private static final String ALGORITHM = "RSA";
    /**          */
    private static String PUBLIC_KEY_FILE = "PublicKey";
    /**          */
    private static String PRIVATE_KEY_FILE = "PrivateKey";
    /** 
     * RSA        
     */
    private static final int MAX_ENCRYPT_BLOCK = 117;
    
    /** *//**
     * RSA        
     */
    private static final int MAX_DECRYPT_BLOCK = 128;
    
 	//    
	public static String encryptOne(String source) throws Exception {
		/**      */
        Key publicKey = getKey(PUBLIC_KEY_FILE);

        /**   Cipher          RSA   */
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] b = source.getBytes();
        /**        */
        byte[] b1 = cipher.doFinal(b);
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(b1);
    }
   //    
   public static String decrypt(String cryptograph) throws Exception {

        Key privateKey = getKey(PRIVATE_KEY_FILE);

        /**   Cipher              RSA   */
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] b1 = decoder.decodeBuffer(cryptograph);

        /**        */
        byte[] b = cipher.doFinal(b1);
        return new String(b);
    }
	//    
	 public static byte[] encrypt(String source) throws Exception {

        Key publicKey = getKey(PUBLIC_KEY_FILE);

        /**   Cipher          RSA   */
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] b = source.getBytes();
        
        int inputLen = b.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        //        
        while (inputLen - offSet > 0)
        {
            if ( inputLen - offSet > MAX_ENCRYPT_BLOCK)
            {
                cache = cipher.doFinal( b, offSet, MAX_ENCRYPT_BLOCK);
            }
            else
            {
                cache = cipher.doFinal( b, offSet, inputLen - offSet);
            }
            out.write( cache, 0, cache. length);
            i++;
            offSet = i * MAX_ENCRYPT_BLOCK;
        }
        byte[] encryptedData = out.toByteArray();
        out.close();
        return encryptedData;
    }
    //    
    public static String decryptByPrivateKey( byte[] encryptedData) throws Exception {
    	Key privateKey = getKey(PRIVATE_KEY_FILE);
    	Cipher cipher = Cipher.getInstance(privateKey.getAlgorithm());
        cipher.init(2, privateKey);
        int inputLen = encryptedData.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
                cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_DECRYPT_BLOCK;
        }
        byte[] decryptedData = out.toByteArray();
        out.close();
        return new String(decryptedData);
    }
    private static Key getKey(String fileName) throws Exception, IOException {
        Key key;
        ObjectInputStream ois = null;
        try {
            /**             */
            ois = new ObjectInputStream(new FileInputStream(fileName));
            key = (Key) ois.readObject();
        } catch (Exception e) {
            throw e;
        } finally {
            ois.close();
        }
        return key;
    }
}

問題1:spring bootプロジェクトは以下の構成を変更する必要がある
private static String PUBLIC_KEY_FILE = "PublicKey";

置換:
private static String PUBLIC_KEY_FILE = "classpath:key/PublicKey.txt";

getKey(String file Name)メソッド内
ois = new ObjectInputStream(new FileInputStream(fileName));

置換
ois = new ObjectInputStream(new FileInputStream(ResourceUtils.getFile(fileName)));

ローカルを置き換えずに走るのは大丈夫ですが、tomcatにパッケージすると静的ファイルが見つかりません.他の項目も同様で、静的ファイルパスを置き換えるだけです.
問題2:戻り値の前段呼び出しまたはjava httpclient呼び出しで復号エラーが発生する
org.apache.commons.codec.binary.Base64 base= new org.apache.commons.codec.binary.Base64(); 
String encodeToString = base.encodeToString(     byte[]);

php呼び出しに上記の問題がない場合、phpには独自のメソッド呼び出しがあります.同じように呼び出されたクライアントも回転する必要があります
 org.apache.commons.codec.binary.Base64 base= new org.apache.commons.codec.binary.Base64(); 
 byte[] cipherTextArray = base64.decode(    String);