Over the last few decades, tremendous and exponential expansion in digital contents together with their applications has emerged. The Internet represents the essential leading factor for this expansion, which provides low-cost communication tools worldwide. However, the main drawback of the Internet is related to security problems. In order to provide secure communication, enormous efforts have been spent in the cryptographic field. Recently, cryptographic algorithms have become essential for increasing information safety. However, these algorithms require random keys and can be regarded as compromised when the random keys are cracked via the attackers. Therefore, it is substantial that the generation of keys should be random and hard to crack. In this paper, this is guaranteed via one of the most efficient nature-inspired algorithms emerged by inspiring the movements of stars, galaxies, and galaxy superclusters in the cosmos that can be utilized with a mathematical model (magic cube) for generating hardly cracking random number keys. In the proposed cryptographic system, the Modified Galactic Swarm Optimization (GSO) algorithm has been utilized in which every row and column of magic cube faces are randomly rotated until reaching the optimal face, and the optimal random elements are selected as optimal key from the optimal face. The generated optimized magic cube keys are used with several versions of RC6 algorithms to encrypt various secret texts. Furthermore, these generated keys are also used for encrypting images using the logical XOR operation. The obtained results of NIST tests proved that the generated keys are random and uncorrelated. Moreover, the security of the proposed cryptographic system was proved