001/*
002 * Trident - A Multithreaded Server Alternative
003 * Copyright 2014 The TridentSDK Team
004 *
005 * Licensed under the Apache License, Version 2.0 (the "License");
006 * you may not use this file except in compliance with the License.
007 * You may obtain a copy of the License at
008 *
009 *    http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017
018package net.tridentsdk.server.netty.packet;
019
020import javax.crypto.Cipher;
021import java.security.Key;
022import java.security.KeyPair;
023import java.security.KeyPairGenerator;
024import java.security.NoSuchAlgorithmException;
025
026/**
027 * Produces RSA encryption digests
028 *
029 * <p>Used to create encrypted packets that the server sends to clients</p>
030 *
031 * @author The TridentSDK Team
032 */
033public final class RSA {
034    private RSA() {
035    }
036
037    /**
038     * Generates a KeyPair with the specified amount of bits using an RSA cipher
039     *
040     * @param bits the bits in the final digest for the KeyPair
041     * @return the KeyPair that has the specified bits and RSA cipher
042     * @throws NoSuchAlgorithmException if RSA cipher is removed in the future
043     */
044    public static KeyPair generate(int bits) throws NoSuchAlgorithmException {
045        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
046        keyGen.initialize(bits);
047
048        return keyGen.generateKeyPair();
049    }
050
051    /**
052     * Decrypts the data into the cipher with the given key
053     *
054     * @param data the data to be ciphered
055     * @param key  the key to use for initialization
056     * @return the decrypted bytes
057     * @throws Exception if something happens to occur
058     */
059    public static byte[] decrypt(byte[] data, Key key) throws Exception {
060        Cipher cipher = Cipher.getInstance("RSA");
061        cipher.init(Cipher.DECRYPT_MODE, key);
062
063        return cipher.doFinal(data);
064    }
065}