简体   繁体   English

使用RSA算法以Java加密文本

[英]Encrypting text in Java using the RSA algorithm

I'm trying to use RSA encryption in Java. 我正在尝试在Java中使用RSA加密。

I'm generating a public key and using it to encrypt text. 我正在生成一个公共密钥,并使用它来加密文本。 My problem is that when I pass in the same text and the same key two time, the encrypted results are different. 我的问题是,当我两次输入相同的文本和相同的密钥时,加密结果是不同的。 This means I can't use my encryption to test if entered text is equal to a stored result of a previous encryption. 这意味着我无法使用加密来测试输入的文本是否等于先前加密的存储结果。

This is my encryption class: 这是我的加密类:

   import java.security.InvalidKeyException;
   import java.security.KeyPair;
   import java.security.KeyPairGenerator;
   import java.security.NoSuchAlgorithmException;
   import java.security.PublicKey;
   import java.util.Arrays;

   import javax.crypto.BadPaddingException;
   import javax.crypto.Cipher;
   import javax.crypto.IllegalBlockSizeException;
   import javax.crypto.NoSuchPaddingException;
   /**
    * The class encrypts text using an RSA algorithm.
    *
    */
   public class RSAEncryption {
       //RSA algorithm
       private final String ALGORITHM = "RSA";

/**
 * The generateKey method generates a public key for use in RSA encryption.
 * @return key a PublicKey for use in RSA encryption.
 */
public PublicKey generateKey(){
    KeyPair key = null;
    KeyPairGenerator keyGen;
    try {
        keyGen = KeyPairGenerator.getInstance(ALGORITHM); //gets instance of the alogrithm
        keyGen.initialize(1024); //a 1021 bit key
        key = keyGen.generateKeyPair(); //makes a pair
    } catch (NoSuchAlgorithmException e) {

        e.printStackTrace();
    }
    return key.getPublic(); //returns the public key. Private key never stored.
}

    /**
    * The encrypt method takes in text and a key and encrypts the text using the RSA encryption algorithm.
    * @params text a String, the text to encrypt.
    * @params key a PublicKey to use in encryption.
    * @returns encryptedText a byte array representing the result of the encryption.

public byte[] encrypt(String text, PublicKey key){
    byte[] encryptedText = null;
    Cipher cipher;
    try {
        cipher = Cipher.getInstance(ALGORITHM); //gets instance of RSA
        cipher.init(Cipher.ENCRYPT_MODE, key); //in encryption mode with the key
        encryptedText = cipher.doFinal(text.getBytes()); //carry out the encryption
    } catch (NoSuchAlgorithmException e) {          
        e.printStackTrace();
    } catch (NoSuchPaddingException e) {            
        e.printStackTrace();
    } catch (IllegalBlockSizeException e) {         
        e.printStackTrace();
    } catch (BadPaddingException e) {           
        e.printStackTrace();
    } catch (InvalidKeyException e) {       
        e.printStackTrace();
    }
    return encryptedText; //return encrypted result
}

/**
 * The authenticate method checks if entered text, once encrypted, matches the stored byte[].
 * @param text a String, the text to encrypt.
 * @param stored a byte[], the result of a prior encryption.
 * @param key a PublicKey, a result of the generateKey method.
 * @return boolean, true if the text is valid, false otherwise.
 */

public boolean authenticate(String text, byte[] stored, PublicKey key){
    byte[] encryptText = encrypt(text,key); //encrypt the entered text
    return Arrays.equals(stored, encryptText); //check if the stored and entered byte[] are the same.
}
} 

I've written JUnit tests for this: 我已经为此编写了JUnit测试:

import static org.junit.Assert.*;

import java.security.PublicKey;
import java.util.Arrays;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;


public class RSAEncryptionTest {

RSAEncryption cipher;
String text;

@Before
public void setUp(){
    cipher = new RSAEncryption();
    text = "text";
}

@Test
public void testEncryptionGenerateKeyGeneratesANewKeyWhenCalled(){

    PublicKey key = cipher.generateKey();

    assertEquals(false,key.equals(cipher.generateKey()));
}

@Test
public void testEncryptionEncryptMethodRepeatablyEncrypts(){

    PublicKey key = cipher.generateKey();

    byte[] encrypted = cipher.encrypt(text,key);
    Assert.assertArrayEquals(encrypted, cipher.encrypt(text,key));
    //test fails
}


@Test
public void testEncryptionAuthenticateMethodReturnsTrueWhenValidTextPassedIn(){

    PublicKey key = cipher.generateKey();

    byte[] encrypted = cipher.encrypt(text,key);

    assertEquals(true,cipher.authenticate(text,encrypted,key));
            //test fails
}


@Test
public void testEncryptionAuthenticateMethodReturnsFalseWhenInvalidTextPassedIn(){

    PublicKey key = cipher.generateKey();

    byte[] encrypted = cipher.encrypt(text,key);

    assertEquals(false,cipher.authenticate("text1",encrypted,key)); 
} 

}

The second and third tests fail. 第二和第三次测试失败。

Any ideas how to repeatably encrypt text using RSA? 有什么想法如何使用RSA重复加密文本吗?

RSA is a public-key encryption scheme. RSA是一种公共密钥加密方案。 It sounds like you actually want to use a hashing algorithm (eg SHA-256 or SHA-512). 听起来您实际上想使用哈希算法(例如SHA-256或SHA-512)。 I say this because you say: 我说这是因为您说:

This means I can't use my encryption to test if entered text is equal to a stored result of a previous encryption. 这意味着我无法使用加密来测试输入的文本是否等于先前加密的存储结果。

If this is your goal, you should use a hashing algorithm. 如果这是您的目标,则应使用哈希算法。 By design, RSA encryption should include a padding step to ensure that the ciphertext differs: 根据设计,RSA加密应包括一个填充步骤,以确保密文不同:

To avoid these problems, practical RSA implementations typically embed some form of structured, randomized padding into the value m before encrypting it. 为了避免这些问题,实际的RSA实现通常在对值m进行加密之前将某种形式的结构化随机填充嵌入到值m中。 This padding ensures that m does not fall into the range of insecure plaintexts, and that a given message, once padded, will encrypt to one of a large number of different possible ciphertexts. 此填充确保m不会落入不安全的明文范围内,并且一旦填充了给定的消息,就将其加密为大量不同的可能密文之一。

-- http://en.wikipedia.org/wiki/RSA_%28algorithm%29 -http://en.wikipedia.org/wiki/RSA_%28algorithm%29

The output of an RSA cipher is not the same each time for a given plaintext when using an appropriate padding scheme (generally PKCS#1 or OAEP padding). 使用适当的填充方案(通常为PKCS#1或OAEP填充)时,对于给定的明文,RSA密码的输出每次都不相同。 Encrypting a given plaintext will result in different ciphertext each time. 加密给定的明文每次都会得到不同的密文。 If the cipher generated the same output for a given input every time it would be a security vulnerability. 如果密码每次为给定的输入生成相同的输出,那将是一个安全漏洞。

That being said you can force Java to use a non padded RSA cipher by using the spec "RSA/ECB/NOPADDING" for Cipher.getInstance(String) . 话虽这么说,您可以通过对Cipher.getInstance(String)使用规范“ RSA / ECB / NOPADDING”来强制Java使用非填充的RSA密码。 Doing so will result in your tests passing, but as I said earlier this is not very secure. 这样做将导致您的测试通过,但是正如我之前所说,这不是很安全。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM