RingJavafor Ring

Hashing and encryption

SHA-256, Base64, AES, secure random numbers and a salted password hash.

What you will learn#

The program#

samples/UsingJava/tutorials/ch11_security.ring
# Tutorial 11: hashing, Base64 and encryption - java.security, java.util.Base64 and javax.crypto
load "java.ring"

using {
	"java.lang"
	"java.util"
	"java.security"
	"javax.crypto"
	"javax.crypto.spec"
	"java.nio.charset"
}

MessageDigest = new MessageDigest
Base64 = new Base64
HexFormat = new HexFormat
Cipher = new Cipher
SecretKeyFactory = new SecretKeyFactory

# 1. a hash: the same text always gives the same 32 bytes, and nothing gives the text back
oDigest = MessageDigest.getInstance("SHA-256")
oHash = oDigest.@digest(new String("Ring").@getBytes("UTF-8"))
? HexFormat.of().formatHex(oHash)

# 2. Base64: bytes as text (the e-mail and web way to carry binary data)
oEncoder = Base64.getEncoder()
cEncoded = oEncoder.encodeToString(new String("Ring meets Java").@getBytes("UTF-8"))
? cEncoded
oBytes = Base64.getDecoder().decode(cEncoded)
? (new String(oBytes)).toString()

# 3. secret key encryption with AES: the same key encrypts and decrypts
oKey = new SecretKeySpec((new String("0123456789abcdef")).@getBytes("UTF-8"),"AES")
oCipher = Cipher.getInstance("AES/ECB/PKCS5Padding")
oCipher.@init([Cipher.ENCRYPT_MODE,oKey])
oSecret = oCipher.@doFinal(new String("a secret message").@getBytes("UTF-8"))
? Base64.getEncoder().encodeToString(oSecret)
oCipher.@init([Cipher.DECRYPT_MODE,oKey])
? (new String(oCipher.@doFinal(oSecret))).toString()

# 4. random numbers that are good for secrets
oRandom = new SecureRandom
oToken = jArray("byte",16)
oRandom.nextBytes(oToken)
? len(HexFormat.of().formatHex(oToken))

# 5. a password hash with a salt: PBKDF2
oFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256")
oSpec = (new PBEKeySpec).@New([ (new String("password")).toCharArray() , (new String("salt1234")).@getBytes("UTF-8") , 1000 , 256 ])
? len(HexFormat.of().formatHex(oFactory.generateSecret(oSpec).getEncoded()))
Output
b3f952e8b6787ce08c5b04c6969fa74919a86c47008d9130cce38483541337b1
UmluZyBtZWV0cyBKYXZh
Ring meets Java
q6POgw1wocCbVBn2bdDPkDdyIuBhqSTFkc2cJ+oWPtQ=
a secret message
32
64

How it works#

A hash always gives the same bytes for the same text and cannot be reversed. Base64 writes bytes as text. AES uses one key to encrypt and decrypt. A password is never stored as is: a salt (random bytes) and many iterations of PBKDF2 make it expensive to guess.

Exercises#

  1. Hash a file instead of a text.
  2. Show that the same text with two different salts gives two hashes.
  3. Encrypt and decrypt a longer text.

Next#

A database

RingJava - use Java classes and methods from Ring programs.