Java中的加密和解密

one*_*ros 10 java encryption

我想将加密的密码存储在Java文件中.我在使用溶液看到javax.crypto中,但这个问题是,目前正在实时生成的关键,这是随机的.

然后,该密码将在运行时在Java程序中获取和解密.鉴于我要将已加密的密码存储在文件中 - 我希望在解密时获得正确的文本.

有没有办法告诉javax.crypto方法:

key = KeyGenerator.getInstance(algorithm).generateKey()
Run Code Online (Sandbox Code Playgroud)

可以用基于某个私钥生成的自己的密钥替换它吗?

谁能指点我一些如何做到这一点的资源?

one*_*ros 24

这是一个使用javax.crypto库和apache commons编解码器库在Base64中进行编码和解码的解决方案,我正在寻找:

import java.security.spec.KeySpec;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import org.apache.commons.codec.binary.Base64;

public class TrippleDes {

    private static final String UNICODE_FORMAT = "UTF8";
    public static final String DESEDE_ENCRYPTION_SCHEME = "DESede";
    private KeySpec ks;
    private SecretKeyFactory skf;
    private Cipher cipher;
    byte[] arrayBytes;
    private String myEncryptionKey;
    private String myEncryptionScheme;
    SecretKey key;

    public TrippleDes() throws Exception {
        myEncryptionKey = "ThisIsSpartaThisIsSparta";
        myEncryptionScheme = DESEDE_ENCRYPTION_SCHEME;
        arrayBytes = myEncryptionKey.getBytes(UNICODE_FORMAT);
        ks = new DESedeKeySpec(arrayBytes);
        skf = SecretKeyFactory.getInstance(myEncryptionScheme);
        cipher = Cipher.getInstance(myEncryptionScheme);
        key = skf.generateSecret(ks);
    }


    public String encrypt(String unencryptedString) {
        String encryptedString = null;
        try {
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] plainText = unencryptedString.getBytes(UNICODE_FORMAT);
            byte[] encryptedText = cipher.doFinal(plainText);
            encryptedString = new String(Base64.encodeBase64(encryptedText));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return encryptedString;
    }


    public String decrypt(String encryptedString) {
        String decryptedText=null;
        try {
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] encryptedText = Base64.decodeBase64(encryptedString);
            byte[] plainText = cipher.doFinal(encryptedText);
            decryptedText= new String(plainText);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return decryptedText;
    }


    public static void main(String args []) throws Exception
    {
        TrippleDes td= new TrippleDes();

        String target="imparator";
        String encrypted=td.encrypt(target);
        String decrypted=td.decrypt(encrypted);

        System.out.println("String To Encrypt: "+ target);
        System.out.println("Encrypted String:" + encrypted);
        System.out.println("Decrypted String:" + decrypted);

    }

}
Run Code Online (Sandbox Code Playgroud)

使用以下输出运行上述程序结果:

String To Encrypt: imparator
Encrypted String:FdBNaYWfjpWN9eYghMpbRA==
Decrypted String:imparator
Run Code Online (Sandbox Code Playgroud)

  • 这个例子对于一些加密函数有很长的路要走,但它会对其他许多函数造成污染.该示例使用`String`作为键.此外,它默默使用不安全的ECB模式加密.也没有真实性或完整性控制.(字符)编码/解码是正常的,默认填充模式也是如此.*但一般来说这段代码**不安全***. (4认同)

Pre*_*raj 17

对称密钥加密:对称密钥使用相同的密钥进行加密和解密.这种类型的密码术的主要挑战是在双方发送者和接收者之间交换密钥.

示例: 以下示例使用对称密钥作为Sun的JCE(J ava C ryptography E xtension)的一部分提供的加密和解密算法.Sun JCE有两层,即加密API层和提供者层.

DES(D ata E ncryption S tandard )是一种流行的对称密钥算法.目前DES已经过时并被认为是不安全的.三重DES和更强的DES变体.它是对称密钥块密码.还有其他的算法,如河豚,Twofish的AES(先进适用é ncryption 小号 TANDARD).AES是DES的最新加密标准.

脚步 :

  1. 添加安全提供程序:我们正在使用JDK提供的SunJCE提供程序.
  2. 生成密钥:使用KeyGenerator和算法生成密钥.我们正在使用DESede.
  3. 编码文本:为了跨平台的一致性,将纯文本编码为字节使用UTF-8 encoding.
  4. 加密文字:实例化CipherENCRYPT_MODE使用的密钥和加密字节.
  5. 解密文本:实例化CipherDECRYPT_MODE使用相同的密钥和解密的字节数.

以上给出的所有步骤和概念都是相同的,我们只是替换算法.

import java.util.Base64;    
import javax.crypto.Cipher;  
import javax.crypto.KeyGenerator;   
import javax.crypto.SecretKey;  
public class EncryptionDecryptionAES {  
    static Cipher cipher;  

    public static void main(String[] args) throws Exception {
        /* 
         create key 
         If we need to generate a new key use a KeyGenerator
         If we have existing plaintext key use a SecretKeyFactory
        */ 
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(128); // block size is 128bits
        SecretKey secretKey = keyGenerator.generateKey();

        /*
          Cipher Info
          Algorithm : for the encryption of electronic data
          mode of operation : to avoid repeated blocks encrypt to the same values.
          padding: ensuring messages are the proper length necessary for certain ciphers 
          mode/padding are not used with stream cyphers.  
         */
        cipher = Cipher.getInstance("AES"); //SunJCE provider AES algorithm, mode(optional) and padding schema(optional)  

        String plainText = "AES Symmetric Encryption Decryption";
        System.out.println("Plain Text Before Encryption: " + plainText);

        String encryptedText = encrypt(plainText, secretKey);
        System.out.println("Encrypted Text After Encryption: " + encryptedText);

        String decryptedText = decrypt(encryptedText, secretKey);
        System.out.println("Decrypted Text After Decryption: " + decryptedText);
    }

    public static String encrypt(String plainText, SecretKey secretKey)
            throws Exception {
        byte[] plainTextByte = plainText.getBytes();
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] encryptedByte = cipher.doFinal(plainTextByte);
        Base64.Encoder encoder = Base64.getEncoder();
        String encryptedText = encoder.encodeToString(encryptedByte);
        return encryptedText;
    }

    public static String decrypt(String encryptedText, SecretKey secretKey)
            throws Exception {
        Base64.Decoder decoder = Base64.getDecoder();
        byte[] encryptedTextByte = decoder.decode(encryptedText);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] decryptedByte = cipher.doFinal(encryptedTextByte);
        String decryptedText = new String(decryptedByte);
        return decryptedText;
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

Plain Text Before Encryption: AES Symmetric Encryption Decryption
Encrypted Text After Encryption: sY6vkQrWRg0fvRzbqSAYxepeBIXg4AySj7Xh3x4vDv8TBTkNiTfca7wW/dxiMMJl
Decrypted Text After Decryption: AES Symmetric Encryption Decryption
Run Code Online (Sandbox Code Playgroud)

资源

示例:具有两种模式的密码,它们是加密和解密的.我们必须在设置模式后每次启动以加密或解密文本. 在此输入图像描述


jam*_*riz 5

KeyGenerator用于生成密钥

您可能要检查KeySpecSecretKeySecretKeyFactory

http://docs.oracle.com/javase/1.5.0/docs/api/javax/crypto/spec/package-summary.html