001package co.codewizards.cloudstore.core.auth;
002
003import static co.codewizards.cloudstore.core.util.Util.*;
004
005import java.security.KeyFactory;
006import java.security.PrivateKey;
007import java.security.spec.EncodedKeySpec;
008import java.security.spec.PKCS8EncodedKeySpec;
009
010import javax.crypto.Cipher;
011import javax.crypto.spec.IvParameterSpec;
012import javax.crypto.spec.SecretKeySpec;
013
014import co.codewizards.cloudstore.core.util.AssertUtil;
015
016public class SignedAuthTokenDecrypter {
017        private PrivateKey privateKey;
018
019        public SignedAuthTokenDecrypter(final byte[] privateKeyData) {
020                AssertUtil.assertNotNull(privateKeyData, "privateKeyData");
021                BouncyCastleRegistrationUtil.registerBouncyCastleIfNeeded();
022                try {
023                        final KeyFactory keyFactory = KeyFactory.getInstance("RSA");
024                        final EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKeyData);
025                        this.privateKey = keyFactory.generatePrivate(privateKeySpec);
026                } catch (final RuntimeException e) {
027                        throw e;
028                } catch (final Exception e) {
029                        throw new RuntimeException(e);
030                }
031        }
032
033        public byte[] decrypt(final EncryptedSignedAuthToken encryptedSignedAuthToken) {
034                AssertUtil.assertNotNull(encryptedSignedAuthToken, "encryptedSignedAuthToken");
035                AssertUtil.assertNotNull(encryptedSignedAuthToken.getEncryptedSignedAuthTokenData(), "encryptedSignedAuthToken.encryptedSignedAuthTokenData");
036                AssertUtil.assertNotNull(encryptedSignedAuthToken.getEncryptedSymmetricKey(), "encryptedSignedAuthToken.encryptedSymmetricKey");
037                try {
038                        final Cipher asymCipher = Cipher.getInstance("RSA/ECB/OAEPWITHSHA1ANDMGF1PADDING");
039                        asymCipher.init(Cipher.DECRYPT_MODE, privateKey);
040                        final byte[] symKey = asymCipher.doFinal(encryptedSignedAuthToken.getEncryptedSymmetricKey());
041
042                        final Cipher symCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
043                        symCipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(symKey, "AES"),
044                                        new IvParameterSpec(encryptedSignedAuthToken.getEncryptedSignedAuthTokenDataIV()));
045
046                        final byte[] signedAuthTokenData = symCipher.doFinal(encryptedSignedAuthToken.getEncryptedSignedAuthTokenData());
047
048                        return signedAuthTokenData;
049                } catch (final RuntimeException e) {
050                        throw e;
051                } catch (final Exception e) {
052                        throw new RuntimeException(e);
053                }
054        }
055}