簡體   English   中英

使用彈性城堡和python PKCS1-OAEP的Java RSA加密

[英]java RSA encryption using bouncy castle and python PKCS1-OAEP

一個多星期以來,我一直在使用來與我的python服務器實現RSA安全通信。

但是,我無法為自己的一生找出所有罐子的正確進口。

我已經包括了在充氣城堡網站上發現的所有罐子,但仍然沒有骰子!

我讀到他們四處移動東西。 如果此代碼過舊或損壞,還有其他使用pkcs1填充的RSA實現嗎?

編輯:

pub鍵位於名為key.pub的文件中。 我如何讀入該文件作為密鑰

-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAv2B0wo+QJ6tCqeyTzhZ3
AtPLgAHEQ/fRYDcR0BkQ+lXEhD277P2fPZwla5AW6szqsjR1olkZEF7IuoI27Hxm
tQHJU0ROhrzstHgK42emz5Ya3BWcm+oq5pLDZnsNDnNlrPncaCT7gHQQJn3YjH8q
aibtB1WCoy7ZJ127QxoKoLfeonBDtt7Qw6P5iXE57IbQ63oLq1EaYUfg8ZpADvJF
b2H3MASJSSDrSDgrtCcKAUYuu3cZw16XShuKCNb5QLsj3tR0QC++7qjM3VcG311K
7gHVjB6zybw+5vX2UWTgZuL6WVtCvRK+WY7nhL3cc5fmXZhkW1Jbx6wLPK3K/JcR
NQIDAQAB
-----END PUBLIC KEY-----

編輯2:基於答案添加殘破的代碼

package Main;


import org.bouncycastle.util.encoders.Base64;

import javax.crypto.Cipher;
import javax.xml.bind.DatatypeConverter;
import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.Security;
import java.security.spec.X509EncodedKeySpec;

public class EncDecRSA {
    public static byte[] pemToDer(String pemKey) throws GeneralSecurityException {
        String[] parts = pemKey.split("-----");
        return DatatypeConverter.parseBase64Binary(parts[parts.length / 2]);
    }

    public static PublicKey derToPublicKey(byte[] asn1key) throws GeneralSecurityException {
        X509EncodedKeySpec spec = new X509EncodedKeySpec(asn1key);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA", "BC");
        return keyFactory.generatePublic(spec);
    }

    public static byte[] encrypt(PublicKey publicKey, String text) throws GeneralSecurityException {
        Cipher rsa = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding", "BC");//PKCS1-OAEP
        rsa.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] cipher =  rsa.doFinal(text.getBytes());
        String s = new String(cipher);
        System.out.print(s);
//        return cipher;
//        return Base64.encode(rsa.doFinal(text.getBytes()));
        cipher = Base64.encode(cipher);
        return cipher;

    }

    static String readFile(String path)
            throws IOException
    {
        String line = null;
        BufferedReader br = new BufferedReader(new FileReader(path));
        try {
            StringBuilder sb = new StringBuilder();
            line = br.readLine();

            while (line != null) {
                sb.append(line);
                sb.append("\n");
                line = br.readLine();
            }
            return sb.toString();
        } finally {
            br.close();

        }

    }
    public static void main(String[] args) throws IOException, GeneralSecurityException {
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

        System.out.println("Working Directory = " +
                System.getProperty("user.dir"));
        String publicKey = readFile("key.public");
        byte[] pem = pemToDer(publicKey);
        PublicKey myKey = derToPublicKey(pem);
        String sendMessage = "{'vid_hash': '917ef7e7be4a84e279b74a257953307f1cff4a2e3d221e363ead528c6b556edb', 'state': 'ballot_response', 'userInfo': {'ssn': '700-33-6870', 'pin': '1234', 'vid': '265jMeges'}}";
        byte[] encryptedDATA = encrypt(myKey, sendMessage);
        Socket smtpSocket = null;
        DataOutputStream os = null;
        DataInputStream is = null;
        try {
            smtpSocket = new Socket("192.168.1.124", 9999);
            os = new DataOutputStream(smtpSocket.getOutputStream());
            is = new DataInputStream(smtpSocket.getInputStream());
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host: hostname");
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection to: hostname");
        }

        if (smtpSocket != null && os != null && is != null) {
            try {
                System.out.println("sending message");
                os.writeBytes(encryptedDATA+"\n");
                os.close();
                is.close();
                smtpSocket.close();
            } catch (UnknownHostException e) {
                System.err.println("Trying to connect to unknown host: " + e);
            } catch (IOException e) {
                System.err.println("IOException:  " + e);
            }
        }
    }
}

其中有以下錯誤:

在此處輸入圖片說明

這是執行此操作的python代碼的一部分:

def _decrypt_RSA(self, private_key_loc, package):
    '''
    param: public_key_loc Path to your private key
    param: package String to be decrypted
    return decrypted string
    '''
    from Crypto.PublicKey import RSA 
    from Crypto.Cipher import PKCS1_OAEP 
    from base64 import b64decode 
    key = open('key.private', "r").read() 
    rsakey = RSA.importKey(key) 
    rsakey = PKCS1_OAEP.new(rsakey) 

    decrypted = rsakey.decrypt(package)
    # decrypted = rsakey.decrypt(b64decode(package)) 
    return decrypted

最后:

這是PKCS1-OAEP的填充方案嗎?

這是這項工作的主要要求。

請注意,我已經嘗試過使用base64編碼和不使用

此示例適用於SpongyCastle-BouncyCastle的Android重新打包。 正如您所注意到的,它們有所不同。 但是,使用Java進行加密如此簡單

將Base64編碼的密鑰字符串轉換為ASN.1 DER編碼的字節數組

public static byte[] pemToDer(String pemKey) throws GeneralSecurityException {
    String[] parts = pemKey.split("-----");
    return DatatypeConverter.parseBase64Binary(parts[parts.length / 2]);
}

將ASN.1 DER編碼的公鑰轉換為PublicKey對象

public static PublicKey derToPublicKey(byte[] asn1key) throws GeneralSecurityException {
    X509EncodedKeySpec spec = new X509EncodedKeySpec(asn1key);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA", "BC");
    return keyFactory.generatePublic(spec);
}

加密數據

public static byte[] encrypt(PublicKey publicKey, String text) throws GeneralSecurityException {
    Cipher rsa = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding", "BC");
    rsa.init(Cipher.ENCRYPT_MODE, publicKey);
    return rsa.doFinal(text.getBytes());
}

bcprov-jdk15on-150.jar是唯一需要的jar。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM