2017-12-13 1 views
-4

이것은 나중에 참조 할 수 있도록 salt, iv 암호화 된 텍스트를 mysql 데이터베이스에 입력하기 위해 작성한 내 암호화 방법입니다. salt, iv 및 암호화 된 텍스트의 값은 각각 blob, blob 및 longblob 데이터 유형에 저장됩니다 (mysql에서).아래의 AES 암호화 코드는 해독 부분에 대해 BadPaddingException을 제공합니다.

package enigma; 

import java.sql.*; 

import java.security.AlgorithmParameters; 
import java.security.InvalidAlgorithmParameterException; 
import java.security.InvalidKeyException; 
import java.security.NoSuchAlgorithmException; 
import java.security.SecureRandom; 
import java.security.spec.InvalidKeySpecException; 
import java.security.spec.InvalidParameterSpecException; 
import java.security.spec.KeySpec; 
import java.sql.ResultSet; 
import java.util.Arrays; 
import java.util.logging.Level; 
import java.util.logging.Logger; 
import javax.crypto.BadPaddingException; 
import javax.crypto.Cipher; 
import javax.crypto.IllegalBlockSizeException; 
import javax.crypto.NoSuchPaddingException; 
import javax.crypto.SecretKey; 
import javax.crypto.SecretKeyFactory; 
import javax.crypto.spec.IvParameterSpec; 
import javax.crypto.spec.PBEKeySpec; 
import javax.crypto.spec.SecretKeySpec; 

/** 
* 
* @author 
*/ 
public class encryptedtexttomysql { 


/** 
* 
* @author USER 
    * @param plaintext 
*/ 
public void enc(String plaintext){ 

try{ 
     Class.forName("java.sql.Driver"); 
     Connection con = DriverManager.getConnection("jdbc:mysql://localhost/test","root","student"); 
     Statement stmt = con.createStatement();    
     // password to encrypt the file 
     String password = "student"; 
     // salt is used for encoding 
      byte[] salt = new byte[8]; 
      SecureRandom secureRandom = new SecureRandom(); 
      secureRandom.nextBytes(salt); 
      SecretKeyFactory factory = SecretKeyFactory 
        .getInstance("PBKDF2WithHmacSHA1"); 
      KeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt, 65536, 
        128); 
      SecretKey secretKey = factory.generateSecret(keySpec); 
      SecretKey secret = new SecretKeySpec(secretKey.getEncoded(), "AES"); 
      // 
      Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); 
      AlgorithmParameters params = cipher.getParameters(); 
      byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV(); 
      cipher.init(Cipher.ENCRYPT_MODE, secret , new IvParameterSpec(iv)); 
      //file encryption method 
      byte[] output = cipher.doFinal((plaintext).getBytes());     
      String query = "INSERT INTO enc values(\""+salt +"\",\""+ iv+"\",\""+ output+"\");"; 
     stmt.executeUpdate(query); 
      System.out.println("File Encrypted."); 
      stmt.close(); 
     con.close(); 
     System.out.println("connection successful !"); 
} 
catch( ClassNotFoundException | SQLException | InvalidKeyException | NoSuchAlgorithmException | InvalidKeySpecException | InvalidParameterSpecException | BadPaddingException | IllegalBlockSizeException | NoSuchPaddingException e){ 
    System.out.println(e); 
}  catch (InvalidAlgorithmParameterException ex) { 
      Logger.getLogger(encryptedtexttomysql.class.getName()).log(Level.SEVERE, null, ex); 
     } 

    } 

} 

이 방법은 데이터베이스에서 값을 허용하고 암호화 된 텍스트를 해독하는 데 사용하기 위해 작성됩니다. 염, 4의 값은 데이터베이스 encrytedtext는

여기
package enigma; 

import java.io.FileInputStream; 
import java.io.FileOutputStream; 
import java.security.AlgorithmParameters; 
import java.security.InvalidAlgorithmParameterException; 
import java.security.InvalidKeyException; 
import java.security.NoSuchAlgorithmException; 
import java.security.SecureRandom; 
import java.security.spec.InvalidKeySpecException; 
import java.security.spec.InvalidParameterSpecException; 
import java.security.spec.KeySpec; 
import java.sql.Connection; 
import java.sql.DriverManager; 
import java.sql.ResultSet; 
import java.sql.SQLException; 
import java.sql.Statement; 
import java.util.logging.Level; 
import java.util.logging.Logger; 
import javax.crypto.BadPaddingException; 
import javax.crypto.Cipher; 
import javax.crypto.IllegalBlockSizeException; 
import javax.crypto.NoSuchPaddingException; 
import javax.crypto.SecretKey; 
import javax.crypto.SecretKeyFactory; 
import javax.crypto.spec.IvParameterSpec; 
import javax.crypto.spec.PBEKeySpec; 
import javax.crypto.spec.SecretKeySpec; 

/** 
* 
* @author 
*/ 
public class decryptetextfrommysql { 

    public String dec(){ 
byte [] salt; 
byte [] enctext ; 
byte[] output = null; 
    //this is to get values from the mysql database  
try{ 
     Class.forName("java.sql.Driver"); 
     Connection con = DriverManager.getConnection("jdbc:mysql://localhost/test","root","student"); 
     Statement stmt = con.createStatement(); 
     String sql = ("SELECT * FROM enc;"); 
     ResultSet rs = stmt.executeQuery(sql); 
     byte [] iv = null; 
     while(rs.next()) { 
     salt = rs.getBytes("salt"); 
     iv = rs.getBytes("iv"); 
     enctext= rs.getBytes("encryptedtext"); 
     } 
     String password = "student"; 
     salt = new byte[8]; 
     enctext = new byte[64]; 
    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); 
    KeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt, 65536, 128); 
    SecretKey tmp = factory.generateSecret(keySpec); 
    SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES"); 
     // file decryption method 
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); 
     iv = new byte[16]; 
    cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv)); 
     output = cipher.update(enctext); 
    output = cipher.doFinal(); 
     //printing out the confirmation 
    System.out.println("File Decrypted! hurray !"); 
    System.out.println("File Decrypted."); 
     stmt.close(); 
     con.close(); 
     rs.close(); 
    System.out.println("connection successful !"); 
} 
catch(ClassNotFoundException | SQLException ex){ 
    System.out.println(ex); 
} 
catch(NoSuchAlgorithmException | InvalidKeySpecException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException ex) { 
Logger.getLogger(decryptetextfrommysql.class.getName()).log(Level.SEVERE, null, ex); 
System.out.println(ex); 
} 
    return new String(output);  
} 

} 

내가 방법을 호출하고이를 사용한 방법이다 LONGBLOB 데이터 유형, 얼룩, 블롭에 저장된다.

javax.crypto.BadPaddingException: Given final block not properly padded 
SEVERE: null 
�� A� I� wd�� 彟� 6�� A� I� wd�� 彟� 6�� A� I� wd�� 彟� 6 
javax.crypto.BadPaddingException: Given final block not properly padded 
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java: 966) 
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java: 824) 

at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java: 436) 
at javax.crypto.Cipher.doFinal(Cipher.java: 2048) 

기본적으로의 doFinal 방법에서 문제가있다 : 여기
encryptedtexttomysql obj4 = new encryptedtexttomysql(); 
decryptetextfrommysql obj5 = new decryptetextfrommysql(); 
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {           

    String plaintext = ta1.getText(); 
    obj4.enc(plaintext); 
}           

private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {           

    String a = obj5.dec(); 
    System.out.println(a); 

출력 예외이다.

String query = "INSERT INTO enc values(\""+salt +"\",\""+ iv+"\",\""+ output+"\");"; 

작동하지 않습니다 즉, 쉽게 발생할 패딩 오류를 트리거 할 수 있습니다

+1

는 ... 적어도 코드를 게시하는 경우 - 가독성과 도움이 결과적으로 준비를 높이기 위해 많은 도움이! (빈 줄과 불필요한 주석이 많이있다.) 또 다른 도움은 예외가 생성 된 줄을 정확하게 알 수있는 것이다. (보통 예외의 StackTrace에 포함) –

+1

1. 'PBEKeySpec' 소금과 IV는 비밀로 할 필요가 없다. 광고는 암호화 된 데이터 앞에 추가 될 수 있습니다. 2. 샘플 데이터를 추가하고 [mcve]를 제공하십시오. 3. Carlos가 코드 정리에 대해 언급했듯이, 코드에 대해 충분히 신경 쓰지 않는다면 왜 다른 사람에게해야할까요? – zaph

+0

확실히 당신의 조언에 payheed 것입니다 – DAGS

답변

0

이 문을 텍스트로 바이너리 데이터를 처리하고 있습니다. 이 같은 Also, your code are open to SQL injection, please use prepared statement.

시도 뭔가 : 당신이 서식 및 들여 쓰기에 좀 더주의를 기울여야한다

PreparedStatement stmt = con.prepareStatement("INSERT INTO enc (salt, iv, encryptedText) VALUES (?, ?, ?)"); 
stmt.setBlob(1, salt); 
stmt.setBlob(2, iv); 
stmt.setBlob(3, output); 
stmt.executeUpdate(); 
+0

위의 명령문을 사용하여 mysql에 입력 된 데이터는 blob 데이터 유형 – DAGS

+0

에 데이터를 입력합니다. blob에 텍스트 데이터를 삽입하는 sql 문을 작성합니다. 데이터는 바이트 [] -> 텍스트 -> 블롭 - 임의의 바이너리 데이터는 일반적으로 살아남지 않습니다. 출력 한 바이너리 데이터를 살펴보고 ' '의 수를 관찰하십시오. 이들은 텍스트로 변환하려고 시도한 바이트를 나타내지 만 할 수 없습니다. 데이터베이스에있는 데이터는 데이터가 아닙니다. 암호화에서 빠져 나왔다. –

+0

어떻게 소금과 iv와 함께 mysql에 암호화 된 텍스트를 저장합니까? – DAGS

관련 문제