在继续使用Java中的println之前,如何使代码等待对象?

时间:2017-04-17 19:41:04

标签: java encryption

我有一个代码,它通过扫描方法加密到Aes-128并加密它。程序运行时,加密终止而不等待响应。我试过了

    try {

         Thread.sleep(10000);

    } catch(InterruptedException ex) {

         Thread.currentThread().interrupt();
    }

但如果我输入的东西很长,它会加密

  

java.util.Scanner [delimiters = \ p {javaWhitespace} +] [position = 0] [match valid = false] [need input = false] [source closed = false] [skipped = false] [group separator = \,] [decimal separator =。] [positive prefix =] [negative prefix = \ Q- \ E] [positive suffix =] [negative suffix =] [NaN string = \Q \ E] [infinity string = \ Q ∞\ E]

无需等待扫描仪的响应。

以下是代码(来自:http://aesencryption.net/的修改后的代码):

    package package1;

    import java.io.UnsupportedEncodingException;
    import java.security.MessageDigest;
    import java.security.NoSuchAlgorithmException;
    import java.util.*;
    import javax.crypto.Cipher;
    import javax.crypto.spec.SecretKeySpec;
    import org.apache.commons.codec.binary.Base64;

    public class AesOne{


    private static SecretKeySpec secretKey;
    private static byte[] key;


    private static String decryptedString;
    private static String encryptedString;

public static void setKey(String myKey){


    MessageDigest sha = null;
    try {
        key = myKey.getBytes("UTF-8");
        System.out.println(key.length);
        sha = MessageDigest.getInstance("SHA-1");
        key = sha.digest(key);
        key = Arrays.copyOf(key, 16);
        System.out.println(key.length);
        System.out.println(new String(key,"UTF-8"));
        secretKey = new SecretKeySpec(key, "AES");


    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }



}

public static String getDecryptedString() {
    return decryptedString;
}
public static void setDecryptedString(String decryptedString) {
    AesOne.decryptedString = decryptedString;
}
public static String getEncryptedString() {
    return encryptedString;
}
public static void setEncryptedString(String encryptedString) {
    AesOne.encryptedString = encryptedString;
}
public static String encrypt(String strToEncrypt)
{
    try
    {
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");

        cipher.init(Cipher.ENCRYPT_MODE, secretKey);


        setEncryptedString(Base64.encodeBase64String(cipher.doFinal(strToEncrypt.getBytes("UTF-8"))));

    }
    catch (Exception e)
    {

        System.out.println("Error while encrypting: "+e.toString());
    }
    return null;
}
public static String decrypt(String strToDecrypt)
{
    try
    {
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");

        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        setDecryptedString(new String(cipher.doFinal(Base64.decodeBase64(strToDecrypt))));

    }
    catch (Exception e)
    {

        System.out.println("Error while decrypting: "+e.toString());
    }
    return null;
}
public static void main(String args[])
{



            System.out.println("What would you like to encrypt?");

            Scanner encrypt = new Scanner(System.in);
            String toEncrypt = encrypt.toString();

            final String strToEncrypt = toEncrypt;
            final String strPssword = "encryptor key";
            AesOne.setKey(strPssword);

            AesOne.encrypt(strToEncrypt.trim());

            System.out.println("String to Encrypt: " + strToEncrypt); 
            System.out.println("Encrypted: " + AesOne.getEncryptedString());

            final String strToDecrypt =  AesOne.getEncryptedString();
            AesOne.decrypt(strToDecrypt.trim());

            System.out.println("String To Decrypt : " + strToDecrypt);
            System.out.println("Decrypted : " + AesOne.getDecryptedString());

}

}

(我认为这里的缩进可能很奇怪)

2 个答案:

答案 0 :(得分:2)

你必须使用

String toEncrypt = encrypt.next(); 

而不是

String toEncrypt = encrypt.toString(); 

然后扫描仪将等待,直到按下Enter键。

.toString()会立即停止等待进程,并提供当前Scanner内容的字符串表示。

答案 1 :(得分:1)

我尝试了代码并且它工作正常....如果你从单元测试(即在JUnit中)踢掉它,那么单元测试线程可能在响应返回之前结束。我有长期(呃)运行任务的问题。 如果是单元测试,您可以尝试添加像这样的AfterClass调用来强制单元测试等待......

    @AfterClass
    public static void afterClass() {

        // the threads to finish before we terminate JUNIT
        Thread sleepyThread = new Thread() {
            public void run() {
                // wait for a bit 
                try {
                    this.sleep(5000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        };

        // start the sleepy thread
        try {
            sleepyThread.start();
            sleepyThread.join();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    System.err.println("Done running tests");

    }