我应该以什么格式接受用户对S3的加密密钥,以及如何在Java中读取它

时间:2014-11-05 01:45:41

标签: java encryption amazon-s3

我正在尝试对我发送给S3的数据进行客户端加密。我想将加密密钥作为用户的输入。我应该以什么格式从用户那里获取密钥。

我尝试将输入作为ssh-keygen生成的私钥,并尝试使用Get public key from private in Java中提到的代码读取它。但是我收到以下错误

Exception in thread "main" java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: IOException : algid parse error, not a sequence
at sun.security.rsa.RSAKeyFactory.engineGeneratePrivate(RSAKeyFactory.java:217)
at java.security.KeyFactory.generatePrivate(KeyFactory.java:372)

我使用ssh-keygen -t rsa

生成密钥

1 个答案:

答案 0 :(得分:0)

I want to take encryption keys as input from the user

我没有尝试您的上述需求,但我已经生成了256位密钥来加密和解密我在S3中的数据。

// Code To Generate Secret Key.
KeyGenerator symKeyGenerator = KeyGenerator.getInstance("AES");
symKeyGenerator.init(256);
SecretKey symKey = symKeyGenerator.generateKey();
System.out.println(new String(Base64.encodeBase64(symKey.getEncoded())));

我这样用来下载和上传S3中的对象

// Code To Make Objects Encrypt while uploading and Decrypt while Downloading.

public static void s3WithEncryption(AWSCredentials credentials) {
        String myKeyPair = "KEY_GENERATED_USING_ABOVE_CODE";
        SecretKey mySymmetricKey = new SecretKeySpec(Base64.decodeBase64(myKeyPair.getBytes()), "AES");
        EncryptionMaterials materials = new EncryptionMaterials(mySymmetricKey);
        AmazonS3Client encryptedS3 = new AmazonS3EncryptionClient(credentials, materials);
        try {
            File file = new File("D:/dummy.txt");
            SSECustomerKey sseKey = new SSECustomerKey(myKeyPair);
            PutObjectRequest objectRequest = new PutObjectRequest(bucketName, "withEncrypt/dummy.txt", file);
            encryptedS3.putObject(objectRequest.withSSECustomerKey(sseKey));
            System.out.println("s3WithEncryption: Object uploaded!!!");
            S3Object downloadedObject = encryptedS3.getObject(new GetObjectRequest(bucketName, "withEncrypt/" + file.getName()).withSSECustomerKey(sseKey));
            downloadFile("D:/withEncrption", downloadedObject.getObjectContent(), "Steps to configure unifiedUI.txt");
            System.out.println("s3WithEncryption: Object Downloaded!!!");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            encryptedS3.shutdown();
        }

    }