Java 中的加密和解密

新手上路,请多包涵

我想将加密密码存储在 Java 文件中。我看到了一个使用 javax.crypto 的解决方案,但问题是密钥是动态生成的,而且是随机的。

然后将在运行时在 Java 程序中获取并解密此密码。鉴于我要在文件中存储一个已经加密的密码 - 我想在解密时获得正确的文本。

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

 key = KeyGenerator.getInstance(algorithm).generateKey()

可以用我自己根据某个私钥生成一次的密钥代替吗?

谁能指出一些有关如何执行此操作的资源?

原文由 oneiros 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 499
2 个回答

这是一个使用 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);

    }

}

运行上面的程序会产生以下输出:

 String To Encrypt: imparator
Encrypted String:FdBNaYWfjpWN9eYghMpbRA==
Decrypted String:imparator

原文由 oneiros 发布,翻译遵循 CC BY-SA 3.0 许可协议

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

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

DES数据 加密 标准)是一种流行的 对称 密钥算法。目前 DES 已经过时并且被认为是不安全的。 三重 DES 和更强大的 DES 变体。它是一种对称密钥分组密码。 还有 其他算法,如 BlowfishTwofishAES高级 加密 标准)。 AES 是基于 DES 的最新加密标准。

脚步 :

  1. 添加安全提供程序: 我们正在使用 JDK 提供的 SunJCE 提供程序。
  2. 生成密钥: 使用 KeyGenerator 和算法生成密钥。我们正在使用 DESedeDESede 是 3DES 实现的描述性名称:DESede = DES-Encrypt-Decrypt-Encrypt = Triple DES)。
  3. 编码文本: 为了跨平台的一致性,使用 UTF-8 encoding 将纯文本编码为字节。
  4. 加密文本: 用 --- 实例化 Cipher ENCRYPT_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;
    }
}

输出:

 Plain Text Before Encryption: AES Symmetric Encryption Decryption
Encrypted Text After Encryption: sY6vkQrWRg0fvRzbqSAYxepeBIXg4AySj7Xh3x4vDv8TBTkNiTfca7wW/dxiMMJl
Decrypted Text After Decryption: AES Symmetric Encryption Decryption

资源

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

原文由 Premraj 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题